Symfony 表单 - 在 CollectionType 中的子条目类型中访问实体 [英] Symfony form - Access Entity inside child entry Type in a CollectionType
本文介绍了Symfony 表单 - 在 CollectionType 中的子条目类型中访问实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试访问 FormBuilder
中父 CollectionType
中给定嵌入表单的实体:
I'm trying to access the entity for a given embedded form in the parent CollectionType
inside FormBuilder
:
ParentType
Class ParentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('children', CollectionType::class, array(
'entry_type' => ChildType::class
);
}
}
儿童类型
class ChildType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$child = $builder->getData(); // this returns null
}
public function getDefaultOptions(array $options)
{
return array(
'data_class' => 'VendorBundleEntityChild',
);
}
}
虽然这在正常形式下有效,但 $child
被返回为 null.如何访问 ChildType
中的 Child
实体?
While this works in a normal form, $child
is being returned as null. How can I access the Child
entity inside ChildType
?
推荐答案
答案在于使用 Event Listeners 来监听 PRE_SET_DATA
事件.
The answer lies in using Event Listeners which listen for the PRE_SET_DATA
event.
它会给你的闭包传递一个 FormEvent
类,它包含表单和绑定到它的数据.
It will pass your closure a FormEvent
class which contains both the form and the data being bound to it.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->addEventListener(FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($builder)
{
$form = $event->getForm();
$child = $event->getData();
if ($child instanceof Child) {
// Do what ever you like with $child entity data
}
}
);
}
这篇关于Symfony 表单 - 在 CollectionType 中的子条目类型中访问实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文