I am trying to generate a Pdf with KnpSnappyBundle and save the position in doctrine when my Bill Entity is generated.
I need the tamplating service for that, which i can't get inside an Entity.
I read into EventListener and tried to get one to work.
My config.yml
services:
bill.listener:
class: MyCompany\CompanyBundle\EventListener\BillListener
tags:
- { name: doctrine.event_listener, event: onFlush }
And my Listener
namespace MyCompany\CompanyBundle\EventListener;
use Doctrine\ORM\Event\OnFlushEventArgs;
class BillListener
{
public function onFlush(OnFlushEventArgs $args)
{
$em = $args->getEntityManager();
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityInsertions() as $insertions) {
foreach ($insertions as $entity) {
if ($entity instanceof Bill) {
$entity->setFilename("test.pdf");
$md = $em->getClassMetadata(get_class($entity));
$uow->recomputeSingleEntityChangeSet($md, $entity);
}
}
}
}
}
My Bill Entity has a setFilename function where I want to save the position of the generated Bill. But i can't get even that to work.
Stop messing with the UOW (it's kind of hacking), just flush it again:
Config
services:
bill.listener:
class: MyCompany\CompanyBundle\EventListener\BillListener
arguments: ["@pdf_service"]
tags :
- { name: doctrine.event_subscriber, connection: default }
Listener
<?php
namespace MyCompany\CompanyBundle\EventListener;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Doctrine\Common\EventSubscriber;
use Doctrine\ORM\Event\OnFlushEventArgs;
use Doctrine\ORM\Event\PostFlushEventArgs;
use MyCompany\CompanyBundle\Service\MyPDFService;
use MyCompany\CompanyBundle\Entity\Bill;
class BillListener implements EventSubscriber
{
protected $pdfs;
protected $bills;
public function __construct(MyPDFService $pdfs)
{
$this->pdfs = $pdfs;
}
public function getSubscribedEvents()
{
return [
'onFlush',
'postFlush'
];
}
public function onFlush(OnFlushEventArgs $event)
{
$this->bills = [];
/* @var $em \Doctrine\ORM\EntityManager */
$em = $event->getEntityManager();
/* @var $uow \Doctrine\ORM\UnitOfWork */
$uow = $em->getUnitOfWork();
foreach ($uow->getScheduledEntityInsertions() as $entity) {
if ($entity instanceof Bill) {
$this->bills[] = $entity;
}
}
}
public function postFlush(PostFlushEventArgs $event)
{
if (!empty($this->bills)) {
/* @var $em \Doctrine\ORM\EntityManager */
$em = $event->getEntityManager();
foreach ($this->bills as $bill) {
/* @var $bill \MyCompany\CompanyBundle\Entity\Bill */
$this->pdfs->generateFor($bill);
$em->persist($bill);
}
$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