2012-01-31 127 views
5

Im通过AJAX改变一些领域,当我试图保存一个表格时,我收到一个错误Extra fields are not allowedSymfony 2形成额外的字段

如何在sf1.4中更改验证器属性,如validatorPass()
或其可能的变化形式接受额外的领域?

我使用SonataAdminBundle来创建表单。

回答

20

你可以将它们结合的形式之前从请求数据的额外字段:

// 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); 
+0

正是我期待的@rogerh,非常感谢你! – Serg 2012-06-15 15:00:42

+0

在我的情况下,我不得不将第一行更改为: $ data = $ request-> request-> get($ form-> getName()); – Serg 2012-06-15 15:17:42

+0

有没有办法在eventSubscriber中获取$ request,让这个解决方案可以在$ builder添加eventSubscriber的所有表单上工作? – Simon 2014-02-12 22:15:47

0

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

  • 创建一个动态的窗体,您可以添加额外的字段。

你对此如何在github工作的一个例子: https://github.com/Keirua/KeiruaProdCustomerDemoBundle

和完整的教程在这个地址(但在法国):

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

PS:看来索纳塔使用这种方式来添加字段。

+0

嗯..字段与实体有很多关系。但是我只想列出与一个类别相关的元素。 – Pawel 2012-01-31 12:38:49

+0

使用的关系是OneToMany,因为您创建了一个将链接到类别的新元素。 – Chopchop 2012-02-13 11:19:54

1

在我的情况的解决方案是非常简单,只需添加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选项添加到收集字段。

+0

这可以工作。谢谢。 – TrtG 2014-04-29 12:55:58