2012-01-31 62 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