我有一个表单字段,它是另一个实体的集合。目标是在创建故障单时,它会创建初始条目,该条目设置为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=" <div class="form-group"><label class="required">__name__label__</label><div id="form_supportEntries___name__"><div class="form-group"><label for="form_supportEntries___name___comment" class="required">Comment</label><textarea class="form-control" id="form_supportEntries___name___comment" name="form[supportEntries][__name__][comment]" required="required"></textarea></div></div></div>"></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
有关答案 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()
),这会设置一个标志,在再次呈现同一表单字段之前会对其进行检查。