Symfony表单 - 子条目中的访问实体输入CollectionType [英] Symfony form - Access Entity inside child entry Type in a CollectionType

查看:97
本文介绍了Symfony表单 - 子条目中的访问实体输入CollectionType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试访问 FormBuilder 中的父 CollectionType 中的给定嵌入式窗体的实体: / p>

父类型

  Class ParentType extends AbstractType 
{
public function buildForm(FormBuilderInterface $ builder,array $ options)
{
$ builder-> add('children',CollectionType :: class,array(
'entry_type'=> ChildType :: class
);
}
}

ChildType

  class ChildType extends AbstractType 
{
public function buildForm(FormBuilderInterface $ builder,array $ options)
{
$ child = $ builder-> getData(); //返回null
}

public function getDefaultOptions(array $ options)
{
return array(
'data_class'=>'Vendor\Bundle\Entity \\ Child',
);
}
}

这以正常形式工作, $ child 正被返回为空。如何访问 ChildType 中的 Child 实体?

解决方案

答案在于使用事件侦听器,该侦听器侦听 PRE_SET_DATA 事件。



它会传递你的关闭一个 FormEvent 类,其中包含绑定到表单和数据的

  public function buildForm(FormBuilderInterface $ builder,array $ options)
{
$ builder-> addEventListener(FormEvents :: PRE_SET_DATA ,
函数(FormEvent $ event)use($ builder)
{
$ form = $ event-> getForm();
$ child = $ event-> getData ();

if($ child instanceof Child){

//做你喜欢的$子实体数据

}
}
);
}


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
        );
    }
}

ChildType

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' => 'Vendor\Bundle\Entity\Child',
        );
    }
}

While this works in a normal form, $child is being returned as null. How can I access the Child entity inside ChildType?

解决方案

The answer lies in using Event Listeners which listen for the PRE_SET_DATA event.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆