Symfony:从子表单获取数据(CollectionType)

Sli*_*nTN 5 symfony-forms symfony

我在两个实体之间有一个 ManyToOne 关系ParentChild因此在FormType我使用的关系中CollectionType,如下所述:

class ParentType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('childs', CollectionType::class, array(
                'entry_type' => ChildType::class,
            ));
    }
}
Run Code Online (Sandbox Code Playgroud)

在 ChildType 类中,我想使用 EventListener 获取嵌入对象:

class ChildType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('lastName');

        $builder->addEventListener(
            FormEvents::POST_SET_DATA,//---after setting data
            function (FormEvent $event) {
                die(var_dump($event->getData()));//---this gives me null
            }
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

尽管我已将完整对象传递给控制器​​中的表单,但我得到的结果为 null:

$parent = new Parent('Test');
$childs = array(
    'test1' => 'test1',
    'test2' => 'test2',
);
foreach ($childs as $key => $value){
    $c = new Child($key, $value);
    $parent->addChild($c);
}

$form = $this->createForm(ParentType::class, $parent);
Run Code Online (Sandbox Code Playgroud)

班级Parent

class Parent{
   /**
     * @var ArrayCollection*
     * @ORM\OneToMany(targetEntity="Child", mappedBy="parent", cascade={"persist", "remove"})
     * @ORM\JoinColumn(nullable = true)
     */
    private $childs;

    /**
     * Constructor
     */
    public function __construct()
    {
         $this->childs= new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Add child
     *
     * @param \AppBundle\Child $child
     *
     * @return Parent
     */
    public function addChild(\AppBundle\Child $child)
    {
        $this->childs[] = $child;

        return $this;
    }

    /**
     * Remove child
     *
     * @param \AppBundle\Child $child
     */
    public function removeChild(\AppBundle\Child $child)
    {
        $this->childs->removeElement($child);
    }

    /**
     * Get childs
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getChilds()
    {
        return $this->childs;
    }
}
Run Code Online (Sandbox Code Playgroud)