whitebear
whitebear

Reputation: 12433

How to remove galleryhasmedia from gallery sonatamediabundle

I am trying to remove galleryhasmedia from gallery.

However gallery entity doesn't have removegalleryhasmedia or something.

so I did a clumsy way, but it doesnt work.

$em = $this->getDoctrine()->getManager();

$firstGhmArray = $gallery->getGalleryHasMedias();
echo count($gallery->getGalleryHasMedias()) // before count
$afterGhmArray = array();
foreach ($firstGhmArray as $ghm){

        if ($ghm->getId() == $id){ // id is the target id to delete
                //delete    
        }
        else {
            array_push($afterGhmArray , $ghm);
        }
        $gallery->setGalleryHasMedias($afterGhmArray);
    }
echo count($gallery->getGalleryHasMedias()) // after count
$em->persist($gallery);
$em->flush();

I think if galleryHasMedias are normal array collection.

I can delete the element with this procedure.

I need to do something more for galleryhasmedia??

Upvotes: 1

Views: 351

Answers (1)

Nawfal Serrar
Nawfal Serrar

Reputation: 2263

You can override the Gallery entity and add this function to it :

    public function clearGalleryHasMedias()
    {
        $this->galleryHasMedias->clear();
    }

galleryHasMedias field is an ArrayCollection which can be cleared using the clear method. Its weird tho that setting an empty array doesn't clear work but i guess my solution is worth the shot.

Upvotes: 1

Related Questions