在嵌入式表单集合中获取实体

时间:2019-03-06 12:03:49

标签: symfony symfony-forms symfony4

在我的编辑表单中,我需要获取嵌入形式的实体对象。这是我的主要编辑形式:

class OrderCollectionsEditType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('sampleCollections', CollectionType::class, [
                'entry_type' => SampleCollectionType::class,
                'allow_add' => true,
                'allow_delete' => true,
                'by_reference' => false
            ])
        ;
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Order::class,
        ]);
    }
}

和嵌入式的:

class SampleCollectionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $sampleCollection = $builder->getData();
        $builder
            ->add('methods', EntityType::class, [
                'class' => Method::class,
                'multiple' => true,
            ])
            {...}
        ;
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => SampleCollection::class,
        ]);
    }
}

在控制器中创建的表单:

$form = $this->createForm(OrderCollectionsEditType::class, $order);

问题是$sampleCollection返回NULL,但是值正确填充了表单。还有其他获取实体对象的方法吗?

2 个答案:

答案 0 :(得分:1)

该对象在$options['data]属性中传递给表单。 而不是$sampleCollection = $builder->getData();,请$sampleCollection = $options['data];

答案 1 :(得分:0)

不幸的是,以上$options['data']的建议不适用于CollectionType,没有“数据”索引。经过更深入的研究,我找到了解决方案,我们可以使用PRE_SET_DATA表单事件,然后在侦听器函数中获取实体对象。

解决方案:

class SampleCollectionType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
                $sampleCollection = $event->getData();

                $form = $event->getForm();
                $form->add('methods', EntityType::class, [
                    'class' => Method::class,
                    'multiple' => true,
                ]);
            }
        ;
    }
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => SampleCollection::class,
        ]);
    }
}