我对edititng嵌入式收藏表单有问题。我有两对多关系的对象。当我用相关的“照片”成功创建一个“良好”的对象时。当我通过添加一些新照片更新Good对象时,所有工作都很好。但是,如果我在删除更新照片后尝试删除某个Good对象中的一张照片。symfony2嵌入式收藏编辑表单问题
Good.php
/**
* @ORM\OneToMany(targetEntity="Photo", mappedBy="good", cascade={"persist", "remove"})
**/
private $photos;
/**
* Add photos
*
* @param \VDKP\Site\BackendBundle\Entity\Photo $photos
* @return Good
*/
public function addPhoto(\VDKP\Site\BackendBundle\Entity\Photo $photos)
{
$photos->setGood($this);
$this->photos->add($photos);
return $this;
}
/**
* Remove photos
*
* @param \VDKP\Site\BackendBundle\Entity\Photo $photos
*/
public function removePhoto(\VDKP\Site\BackendBundle\Entity\Photo $photos)
{
$this->photos->removeElement($photos);
}
/**
* Get photos
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getPhotos()
{
return $this->photos;
}
Photo.php
/**
* @ORM\ManyToOne(targetEntity="Good", inversedBy="photos")
* @ORM\JoinColumn(name="good_id", referencedColumnName="id")
**/
private $good;
GoodController,updateACtion:
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('VDKPSiteBackendBundle:Good')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find Good entity.');
}
$originalPhotos = new \Doctrine\Common\Collections\ArrayCollection();
foreach ($entity->getPhotos() as $photo) {
$originalPhotos->add($photo);
}
$editForm = $this->createEditForm($entity);
$editForm->handleRequest($request);
if ($editForm->isValid()) {
foreach ($originalPhotos as $photo) {
if (false === $entity->getPhotos()->contains($photo)) {
$photo->setGood(null);
$em->persist($photo);
}
}
$em->persist($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('good_edit', array('id' => $id)));
return array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
);
}
我做的一切书面文件here英寸
对不起,我的英语。感谢您的帮助。
我看不到使用'removePhoto()'方法的代码片段 – DonCallisto 2014-10-03 06:42:30
它是'$ photo-> setGood(null);'对我来说看起来不太好。为什么不使用'$ good-> getPhotos() - > removeElement($ photo);'? – Hpatoio 2014-10-03 07:41:54
因为我在照片和好实体之间有多对一的关系 – miheyich 2014-10-03 08:12:24