5

假设这个表单使用了一个虚构的Animal文档对象类,它在ZooCollection中只有两个属性(“名称”和“颜色”)。

我正在寻找一个可行的简单愚蠢的解决方案,用给定的对象自动预填充表单字段(例如更新?)。

Acme/DemoBundle/Controller/CustomController

public function updateAnimalAction(Request $request)
{
    ...
    // Create the form and handle the request
    $form = $this->createForm(AnimalType(), $animal);

    // Set the data again          << doesn't work ?
    $form->setData($form->getData());
    $form->handleRequest($request);
    ...
}
4

2 回答 2

8

您应该加载要更新的动物对象。createForm() 将使用加载的对象来填充表单中的字段。

假设您使用注释来定义您的路线:

/**
 * @Route("/animal/{animal}")
 * @Method("PUT")
 */
public function updateAnimalAction(Request $request, Animal $animal) {
    $form = $this->createForm(AnimalType(), $animal, array(
        'method' => 'PUT', // You have to specify the method, if you are using PUT 
                           // method otherwise handleRequest() can't
                           // process your request.
    ));

    $form->handleRequest($request);
    if ($form->isValid()) {
        ...
    }
    ...
}

我认为从 Symfony 生成的代码和教义控制台命令(教义:generate:crud)中学习总是一个好主意。您可以了解处理此类请求的想法和方式。

于 2013-12-10T17:33:29.210 回答
1

使用对象创建表单是最好的方法(请参阅@dtengeri 的答案)。但是您也可以使用$form->setData()关联数组,这听起来像您所要求的。这在不使用 ORM 或只需要更改表单数据的子集时很有帮助。

最大的问题是表单构建器中的任何默认值都不会setData(). 这是违反直觉的,但这就是 Symfony 的工作方式。讨论:

于 2017-06-16T09:26:42.817 回答