Symfony2 Doctrine prePersist event listener not working

I have a problem with the implementation of the Doctrine EventListener. When creating a new invoice, there is a collection of items (name, price, quantity) that are included in the InvoiceType form. For an invoice, in the price field I want to insert the sum of all purchased products. In the ReportListener, I get the amount, but the EventListener does not save the data, and the code just stops without displaying an error (the program stops when $entityManager->persist($entity) is executed in ReportListener)

Here are some of the code

controller

 class InvoiceController extends Controller { public function createAction(Request $request) { $em = $this->getDoctrine()->getManager(); $company = $em->getRepository('DemoBundle:Company') ->findOneByUser($this->getUser()->getId()); $invoice = new Invoice(); $item = new Item(); $form = $this->createForm(new InvoiceType($company->getId()), $invoice); if($request->isMethod('POST')){ if($form->isValid()){ $em->persist($invoice); $em->flush(); } } } } 

Reportlistener

 namespace Demo\Bundle\EventListener; use Doctrine\ORM\Event\LifecycleEventArgs; use Demo\Bundle\Entity\Invoice; class ReportListener { public function prePersist(LifecycleEventArgs $args) { $entity = $args->getEntity(); $em = $args->getEntityManager(); $priceTotal = 0; foreach ($entity->getItems() as $item) { $price = &$priceTotal; $price += $item->getPrice() * $item->getAmount(); } $entity->setPriceTotal($priceTotal); // this works $em->persist($entity); // here code stops $em->flush(); } } 

service.yml

 report.listener: class: Faktura\FakturaBundle\EventListener\ReportListener tags: - { name: doctrine.event_listener, event: prePersist } 
+4
source share
2 answers

prePersist is an event that is fired, you do not need and should not try to persist and erase yourself in this case, Doctrine will be there when it is ready. Basically, just delete the last lines:

 $em->persist($entity); // here code stops $em->flush(); 
+8
source

your controller is missing $form->handleRequest($request); otherwise, the values ​​from the arent request are assigned to your invoice object.

At your listener, you don’t need to update your score again and again, you just set the necessary properties.

+3
source

Source: https://habr.com/ru/post/1489587/


All Articles