如何在不使用javascript的情况下呈现此表单集合字段?

时间:2014-03-05 15:59:00

标签: php forms symfony doctrine

我有一个表单字段,它是另一个实体的集合。目标是在创建故障单时,它会创建初始条目,该条目设置为onetomany关系。当我将集合设置为'allow_add'和'protoype'为false时,它会呈现一个空div。相当无用。如果我将集合设置为'allow_add'并且'protoype'为true,那么它将表单字段的所有内容放在div的data-protype属性中。

例如:

<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

有关

3 个答案:

答案 0 :(得分: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    
}

这是你想要达到的目标吗?

答案 1 :(得分:2)

在Controller端,初始化第一个SupportEntry:

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

在Twig文件中,使用;

渲染唯一的第一个项目
{{ form_row(form.supportEntries) }}

或更好的类似:

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

答案 2 :(得分:0)

如果只需要一个表单字段,则可以通过以下方式在模板中呈现它:

{{ form_widget(form.support_entries.vars.prototype)|replace({'__name__':1})|raw }}

这仅在先前未调用{{ form_widget(form.support_entries) }}{{ form_row(form.support_entries) }}的情况下有效。

不幸的是,如果您想渲染来自同一集合的多个表单字段(这是我需要做的),则此方法不起作用。这是因为呈现表单字段会导致FormView::setRendered()被调用(通过FormRenderer::searchAndRenderBlock()),这会设置一个标志,在再次呈现同一表单字段之前会对其进行检查。