我在两个实体Parent
和Child
之间有一个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;
}
}