我在实现 Doctrine EventListener 时遇到问题。创建新发票时,InvoiceType
表单中包含一组项目(标题、价格、金额)。对于发票,在该price
字段中,我想插入所有购买产品的总和。在 ReportListener 中,我得到了总和,但 EventListener 不会预先保存数据,并且代码只是停止而没有显示错误($entityManager->persist($entity)
在 ReportListener 中执行时程序停止)
这是一些代码
控制器
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();
}
}
}
}
报告监听器
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();
}
}
服务.yml
report.listener:
class: Faktura\FakturaBundle\EventListener\ReportListener
tags:
- { name: doctrine.event_listener, event: prePersist }