Reputation: 246
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 }
Upvotes: 4
Views: 8248
Reputation: 13814
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();
Upvotes: 9
Reputation: 1941
in your controller its missing the $form->handleRequest($request);
, otherwise the values from request arent assigned to your Invoice Object .
On your listener you dont need to persist and flush your Invoice again, you just set the properties you want.
Upvotes: 3