tom*_*ahh 26 symfony doctrine-orm
我有以下图库实体
class Gallery
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var ArrayCollection
* @ORM\OneToMany(targetEntity="Tessa\GalleryBundle\Entity\Photo", mappedBy="gallery", cascade={"persist", "remove"})
*/
private $photos;
/* ... */
}
Run Code Online (Sandbox Code Playgroud)
这gallery与实体的manyToOne关系有关PointOfInterest.这是宣言
class PointOfInterest
{
/* ... */
/**
* @ORM\ManyToOne(targetEntity="Tessa\GalleryBundle\Entity\Gallery", cascade={"persist", "remove"})
* @ORM\JoinColumn(nullable=false)
*/
private $gallery;
/* ... */
Run Code Online (Sandbox Code Playgroud)
我还使用表单来更新PointOfInterest实体.这是表格声明
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', 'text')
->add('gallery', new GalleryType())
;
}
Run Code Online (Sandbox Code Playgroud)
和GalleryType声明.
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('photos', 'collection', array('type' => new PhotoType(),
'required' => false,
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false
))
;
}
Run Code Online (Sandbox Code Playgroud)
当我编辑时,PoI我可以毫无问题地将照片添加到图库,但我无法删除任何内容.
我试图挂钩画廊PreUpdate,但它永远不会被调用.我用实体removePhotos方法打印输出,Gallery照片从图库中删除.然后我怀疑画廊永远不会坚持下去.
这是我坚持PoI编辑后的代码.
private function handleForm($elem, $is_new)
{
$form = $this->createForm(new CircuitType, $elem);
$request = $this->get('request');
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($elem);
$em->flush();
return $this->redirect($this->generateUrl('tessa_circuit_index'));
}
}
return $this->render('TessaUserBundle:Circuits:add.'.'html'.'.twig',
array(
'form' => $form->createView(),
'is_new' => $is_new,
));
}
Run Code Online (Sandbox Code Playgroud)
gat*_*isl 71
关于处理这种状况的Symfony2食谱有文章.由于您具有OneToMany关系,因此必须在控制器中手动删除相关对象.
编辑:或者您可以使用Doctrine的孤儿删除功能.
class Gallery
{
//...
/**
* @ORM\OneToMany(targetEntity="Photo", mappedBy="gallery", cascade={"persist", "remove"}, orphanRemoval=true)
*/
private $photos;
//...
public function removePhotos($photo)
{
$this->photos->remove($photo);
$photo->setGallery(null);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29680 次 |
| 最近记录: |