无法使用CollectionType的表单事件获取实体

时间:2019-05-17 13:12:53

标签: symfony symfony4 symfony-forms

如果表单元素为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,则会按预期方式打印实体。我该怎么解决?

0 个答案:

没有答案