【问题标题】:Symfony 2 form extra fieldsSymfony 2 形成额外的字段
【发布时间】:2012-01-31 11:29:49
【问题描述】:

我通过 AJAX 更改了一些字段,当我尝试保存表单时,我收到一个错误 Extra fields are not allowed

如何在 sf1.4 中更改像 validatorPass() 这样的验证器属性?
或者它可能会更改表单以接受额外的字段?

我正在使用 SonataAdminBundle 创建表单。

【问题讨论】:

    标签: php forms symfony sonata-admin


    【解决方案1】:

    您可以在将请求数据绑定到表单之前从请求数据中删除额外的字段:

        // The JSON PUT data will include all attributes in the entity, even
        // those that are not updateable by the user and are not in the form.
        // We need to remove these extra fields or we will get a
        // "This form should not contain extra fields" Form Error
        $data = $request->request->all();
        $children = $form->all();
        $data = array_intersect_key($data, $children);
        $form->bind($data);
    

    【讨论】:

    • 就我而言,我必须将第一行更改为: $data = $request->request->get($form->getName());
    • 有没有办法在 eventSubscriber 中获取 $request 以使此解决方案适用于 $builder 添加 eventSubscriber 的所有表单?
    • 它非常适合集成 REST 客户端,例如 Restangular 之类的。谢谢!
    • 谢谢对我有用。我为我的 api 流程表单函数创建了一个函数:gist.github.com/ajankowski/ca28218ac1374c286e90
    【解决方案2】:

    在我的情况下,解决方案非常简单,只需将 allow_add 添加到您的集合字段, 在我的例子下面

            ->add('Details', 'collection', array(
                'type' => new DetailsType(),
                'allow_add' => true,
                'allow_delete' => true,
                'label' => ' '
            ))
    

    你也可以查看这个问题的官方文档 http://symfony.com/doc/current/cookbook/form/form_collections.html

    您需要做的第一件事是让表单集合知道它将接收未知数量的标签。到目前为止,您已经添加了两个标签,并且表单类型预计正好接收两个,否则将抛出错误:此表单不应包含额外的字段。为了使其灵活,请将 allow_add 选项添加到您的集合字段。

    【讨论】:

      【解决方案3】:

      您不能添加额外的字段,因为它们没有在实体中声明。有一个解决方案可以绕过您的问题:

      • 创建一个动态表单,您可以在其中添加额外的字段。

      您有一个关于它如何在 github 上工作的示例: https://github.com/Keirua/KeiruaProdCustomerDemoBundle

      以及此地址的完整教程(但为法语):

      http://blog.keiruaprod.fr/2012/01/18/formulaires-dynamiques-avec-symfony2/

      PS:看来奏鸣曲就是用这种方式添加字段的。

      【讨论】:

      • 嗯.. 字段与实体是多对多相关的。但我只想在列表中列出与一个类别相关的元素。
      • 使用的关系是 OneToMany,因为您创建了一个将链接到类别的新元素。
      猜你喜欢
      • 2013-10-13
      • 2015-06-22
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2011-05-25
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      相关资源
      最近更新 更多