2014-03-05 39 views
0

我有一個表單域是另一個實體的集合。目標是當你創建一張票時,它會創建初始條目,並將其設置爲一個關係。當我將collection設置爲'allow_add'並且'protoype'爲false時,它會渲染一個空的div。很無用。如果我將collection設置爲'allow_add'和'protoype'爲true,那麼它會將表單字段的所有內容放入div的data-protype屬性中。如何在不使用JavaScript的情況下呈現此表單集合字段?

例如:

<div class="form-group"><label>Support Entries</label><div id="form_supportEntries" data-prototype=" &lt;div class=&quot;form-group&quot;&gt;&lt;label class=&quot;required&quot;&gt;__name__label__&lt;/label&gt;&lt;div id=&quot;form_supportEntries___name__&quot;&gt;&lt;div class=&quot;form-group&quot;&gt;&lt;label for=&quot;form_supportEntries___name___comment&quot; class=&quot;required&quot;&gt;Comment&lt;/label&gt;&lt;textarea class=&quot;form-control&quot; id=&quot;form_supportEntries___name___comment&quot; name=&quot;form[supportEntries][__name__][comment]&quot; required=&quot;required&quot;&gt;&lt;/textarea&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt;"></div></div> 

然後,我不得不用這個JavaScript來顯示錶單字段:

<script> 
     var entryFieldHTML = $("#form_supportEntries").attr("data-prototype"); 
     $("#form_supportEntries").html(entryFieldHTML); 
    </script> 

有一次,我跑了JavaScript,它顯示和按預期工作。但是我並不需要這個數據原型屬性,因爲在這個表單上你只能擁有一個supportEntry。

這個問題是涉及到:Symfony form creates new object and create first one-to-many object

回答

2

在您的控制器端,初始化第一SupportEntry:

// My controller, creating the form 
$supportTicket = new SupportTicket(); 
$supportTicket->addSupportEntry(new SupportEntry); // It's the frst item of the collection 

在你的嫩枝文件,渲染,唯一的第一個項目;

{{ form_row(form.supportEntries) }} 

或更好的是這樣的:

{{ form_row(form.supportEntries.children.0) }} 
+0

啊,我明白了。這工作完美。現在唯一的問題是,這是創建,我不知道它來自哪裏 – Dominick

+0

看看我的編輯也許它更好... – AlterPHP

+0

刪除'''在'$ builder'中使用''entry_options'=> ['label'=> false]'作爲字段參數 –

2

你可以恢復到'allow_add' => false,然後使用該控制器的代碼片段:

public function someControllerAction(){ 
    $entity = ...; 

    // It is vital for `supportEntities` property not to be NULL 
    // Add new, blank, sub-entity, since you'll need only one 
    $entity->getSupportEntries()->add(new SupportEntry());  

    $form = $this->createForm(new YourFormClass(), $entity); 

    // REST OF THE LOGIC  
} 

難道這就是你想達到什麼目的?

相關問題