我在实现 Doctrine EventListener 时遇到问题。创建新发票时,InvoiceType
表单中包含一组项目(标题、价格、金额)。对于发票,在 price
字段中,我想插入所有购买产品的总和。在 ReportListener 中,我得到了总和,但 EventListener 没有预先保留数据,代码只是停止而不显示错误(程序在 ReportListener 中执行 $entityManager->persist($entity)
时停止)
这是一些代码
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 是一个被触发的事件,您不必也不应该尝试在该事件中自己持久化和刷新,Doctrine 会在它准备好时到达那里。基本上,只需删除最后几行:
$em->persist($entity); // here code stops
$em->flush();
关于Symfony2 Doctrine 事件监听器 prePersist 不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17458228/