如果表单元素为FormEvent::getData()
,则无法为FormEvents::PRE_SET_DATA
使用CollectionType
的实体:
class FooType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// some elements here
->add('bars', CollectionType::class, [
'entry_type' => BarType::class,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
])
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'data_class' => Foo::class,
'allow_extra_fields' => true,
'csrf_protection' => false,
]
);
}
}
class BarType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('address', Types\TextType::class)
;
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$data = $event->getData();
// NULL is here
dump($data);
exit;
}
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(
[
'data_class' => Bar::class,
'allow_extra_fields' => true,
'csrf_protection' => false,
]
);
}
}
如果我将addEventListener代码块添加到FooType
,则会按预期方式打印实体。我该怎么解决?