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

时间:2017-04-25 13:40:44

标签: symfony symfony-forms

我在两个实体ParentChild之间有一个ManyToOne关系,所以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,
            ));
    }
}

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

虽然我已将完整对象传递给控制器​​中的表单,但我得到的结果为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);

课程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;
    }
}

0 个答案:

没有答案