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 }
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With