如何在Symfony2中使用Form类


How to use Form classes in Symfony2

我正在学习Symfony2中关于如何使用表单类的教程。

我做错了什么,因为当我使用以下示例代码时:

// src/Acme/TaskBundle/Controller/DefaultController.php
// add this new use statement at the top of the class
use Acme'TaskBundle'Form'Type'TaskType;
public function newAction()
{
    //$task = // ... ???
    $form = $this->createForm(new TaskType(), $task);
// ...
}

我收到以下错误:

注意:未定义变量:task

我知道$task还没有被正确定义。有人能向我解释一下我应该如何定义它吗?我尝试将其创建为实体、formType和未定义变量,但都没有成功。

干杯

如果按照第一节的教程进行操作,那么您应该已经在Acme'TaskBundle'Entity命名空间中创建了一个Task实体。所以你的控制器应该是

// src/Acme/TaskBundle/Controller/DefaultController.php
// add this new use statement at the top of the class
use Acme'TaskBundle'Form'Type'TaskType;
use Acme'TaskBundle'Entity'Task;
public function newAction()
{
    $task = new Task();
    $form = $this->createForm(new TaskType(), $task);
// ...
}