Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Doctrine event listener prePersist not working

I have problem with implementing Doctrine EventListener. When creating a new invoice, there is a collection of items (title, price, amount) that is included in InvoiceType form. For an invoice, in the price field, I want to insert the sum of all bought products. In ReportListener, I get the sum, but EventListener does not pre-persist data and code just stops with no error being displayed (program stops when executing $entityManager->persist($entity) in ReportListener)

Here is 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 }
like image 948
123dcck Avatar asked Dec 15 '22 09:12

123dcck


1 Answers

prePersist is an event that is fired, you don't have to and shouldn't try to persist and flush by yourself in that event, Doctrine will get there when it's ready. Basically, simply remove the last couple lines:

$em->persist($entity);                     // here code stops
$em->flush();
like image 90
Pier-Luc Gendreau Avatar answered Feb 12 '23 11:02

Pier-Luc Gendreau