繁体   English   中英

Symfony2 表单用数据预填充字段

[英]Symfony2 Form pre-fill fields with data

假设此时,这种形式利用的假想Animal文档对象类从ZooCollection只有两个在性质(“name”和“颜色”)

我正在寻找一个有效的简单愚蠢的解决方案,以自动神奇地使用给定对象预填充表单字段(例如,用于更新?)。

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);
    ...
}

您应该加载要更新的动物对象。 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 )中学习总是一个好主意。 您可以了解处理此类请求的想法和方式。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM