Symfony2 子表单事件传播


Symfony2 Child Form Events Propagation

我有两个实体。实体 A 是实体 B 的父级。我正在为实体 A 创建一个 REST,其中包含实体 B 作为子项。

class EntityA {
   private $name;
   private $type;
   private $bs;
}
class EntityB {
   private $entityA;
   private $color;
}

我基本上做一个帖子/放,比如:

{ "name": "anamehere", "type": "atypehere", "bs": [{"color": "blue"}] }

对于重要部分,实体 A 的形式如下所示:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name', TextType::class)
        ->add('type', TextType::class)
        ->add('bs', CollectionType::class, array(
            'entry_type' => EntityB::class,
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false,
        ));
    $builder->addEventListener(FormEvents::SUBMIT, array($this, 'onSubmitData'));
}
public function onSubmitData(FormEvent $event) {
    // Do Something
}

我的实体 B 的表单如下所示:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('color', TextType::class);
    $builder->addEventListener(FormEvents::SUBMIT, array($this, 'onSubmitData'));
}
public function onSubmitData(FormEvent $event) {
    // Do Something else
}

我遇到的问题是,当我执行 POST/PUT 时,没有调用提交数据上的实体 B 表单事件。如何将事件从实体 A 窗体传播到实体 B 窗体。它在实体中工作正常

我和你有同样的问题,经过一些测试,我找到了答案,所以我在这里回答,以防其他人在这里找到他的方式:子表单事件有事件传播。

确切的生命周期是:

Parent PRE_SUBMIT
                     Child PRE_SUBMIT
                                        GrandChild PRE_SUBMIT
                                        GrandChild SUBMIT
                                        GrandChild POST_SUBMIT
                     Child SUBMIT
                     Child POST_SUBMIT
Parent SUBMIT
Parent POST_SUBMIT  

关于你的问题,我的猜测是,这是由于您没有在实体A的表单中直接使用实体B的表单,而是实体B的表单类型的CollectionType,并且似乎CollectionType不会自然地为其子级为每个事件调度SUBMIT事件。

希望这对任何人有帮助!