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

问题描述 投票:0回答:2

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

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,但表单由值正确填充。有没有其他方法来获取实体对象?

symfony symfony-forms symfony4
2个回答
1
投票

该对象将传递给$options['data]属性中的表单。而不是$sampleCollection = $builder->getData();$sampleCollection = $options['data];得到它


0
投票

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

SOLUTION:

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,
        ]);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.