当我将表单嵌入到另一个表单中时,我遇到了这个问题,它们有多对一的关系,但是在保存数据时,子节点不会将id保存到数据库中。
假设我的父母实体是大学,孩子是教师。一所大学可以有很多学院。
父。
class University
{
/**
* @ORM\OneToMany(targetEntity="UniversityFaculty", mappedBy="university", cascade={"persist"})
*/
private $faculties;
public function __construct()
{
$this->faculties = new ArrayCollection();
}
/**
* Add faculty
*
* @param UniversityFaculty $faculty
*
* @return University
*/
public function addFaculty(UniversityFaculty $faculty)
{
$this->faculties[] = $faculty;
return $this;
}
/**
* Remove faculty
*
* @param UniversityFaculty $faculty
*/
public function removeFaculty(UniversityFaculty $faculty)
{
$this->faculties->removeElement($faculty);
}
子。
class Faculty
{
/**
* @var University
*
* @ORM\ManyToOne(targetEntity="University", inversedBy="faculties", cascade={"persist"})
* @ORM\JoinColumn(name="university_id", referencedColumnName="id")
*/
private $university;
// ...
我建了一个表格:
->add('faculties', BootstrapCollectionType::class, array(
'type' => UniversityFacultyType::class,
'allow_add' => true,
'allow_delete' => true,
'add_button_text' => 'Add Faculty',
'delete_button_text' => 'Delete Faculty',
'sub_widget_col' => 9,
'button_col' => 3,
'required' => false,
'by_reference' => false
))
BootstrapCollectionType
只是由CollectionType
由BraincraftBootstrapBundle定制,所以我不需要为ADD或REMOVE按钮创建JS和CSS。
我阅读了文档,并且已经在大学实体内部添加了添加和删除方法,cascade={"persist"}
和by_reference => false
,一切正常,但它仍然没有在DB中的Faculty表中保存大学ID(其他列已保存。)
我缺少什么想法?
答案 0 :(得分:1)
您缺少将大学分配给新的学院。
有很多方法可以做到这一点。
例如:
public function addFaculty(UniversityFaculty $faculty)
{
$faculty->setUniversity($this);
$this->faculties[] = $faculty;
return $this;
}
或者:
->add('faculties', BootstrapCollectionType::class, array(
'type' => UniversityFacultyType::class,
'allow_add' => true,
'allow_delete' => true,
'add_button_text' => 'Add Faculty',
'delete_button_text' => 'Delete Faculty',
'sub_widget_col' => 9,
'button_col' => 3,
'required' => false,
'by_reference' => false,
'empty_data' => function (FormInterface $form) {
$faculty = UniversityFaculty();
$faculty->setUniversity($form->getParent()->getData());
return $price;
},
))
也许,大学在$form->getData()
,而不是$form->getParent()->getData()
。但是形式的某个地方