【问题标题】:How to use Form classes in Symfony2如何在 Symfony2 中使用表单类
【发布时间】:2012-03-21 10:47:33
【问题描述】:

我正在关注 Symfony2 的 the tutorial,了解如何使用表单类。

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

// 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 尚未正确定义。谁能向我解释我应该如何定义它?我尝试将它创建为实体、formType、未定义变量,但都没有运气。

干杯

【问题讨论】:

    标签: php forms class symfony formbuilder


    【解决方案1】:

    如果您从一开始就按照教程进行操作,那么您应该已经在 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);
    
    // ...
    }
    

    【讨论】:

    • 感谢 m2mdas。正如你提到的,我确实遵循了手册,但只包括了手册中我出错的部分。然而,错误出现在 taskType 类中。就我而言,它包括以下行: $builder->add('Task');那没有多大意义。 (如果实体 Task 还包含一个名为 Task 的属性,它就会有,但事实并非如此。)现在它可以工作了。感谢您的快速回复!
    猜你喜欢
    • 2013-05-11
    • 1970-01-01
    • 2012-05-23
    • 2014-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多