I have a product entity each product is related to a multiple images when i add a product with multiple images it work but if i remove a product i have a error
in the delete function i have this code :
public function delete(Request $req,Products $product){
if($this->isCsrfTokenValid('delete'. $product->getId(),$req->get('_token'))){
foreach ($product->getImages() as $image) {
$product->removeImage($image);
$this->em->remove($image);
$this->em->persist($image);
}
$this->em->remove($product);
$this->em->flush();
$this->addFlash('success',"product deleted");
}
return $this->redirectToRoute("admin.index");
}
in the edit I have
public function edit(Products $product ,Request $req):Response{
$originalImages = array();
if($product){
foreach ($product->getImages() as $image) {
$originalImages[] = $image;
}
$editForm = $this->createForm(ProductsTypeForm::class,$product);
$editForm->handleRequest($req);
if($editForm->isSubmitted()&&$editForm->isValid()){
foreach ($product->getImages() as $image) {
foreach ($originalImages as $key => $toDel) {
if ($toDel->getId() === $image->getId()) {
unset($originalImages[$key]);
}
}
}
// remove the relationship between the image and the Product
foreach ($originalImages as $image) {
$product->removeImage($image);
$this->em->remove($image);
$this->em->persist($image);
}
$this->em->persist($product);
$this->em->flush();
$this->addFlash('success',"changed");
return $this->redirectToRoute('admin.index');
}
}
return $this->render('pages/admin/edit.html.twig',[
'item'=>$product,
'form'=>$editForm->createView()
]);
}
in the Images entity I have a bidirectional many-to-one relationship. the relationship is removed correctly but the image related to the product did not anyone can help me