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);
service.yml
report.listener: class: Faktura\FakturaBundle\EventListener\ReportListener tags: - { name: doctrine.event_listener, event: prePersist }
source share