2014-03-05 38 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  
} 

难道这就是你想达到什么目的?

相关问题