您好我有一个prePersist和preUpdate监听器:
<?php
namespace FM\AppBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use FM\AdminBundle\Entity\Address\DeliveryAddress;
class DeliveryAddressListener
{
/**
* @param LifecycleEventArgs $args
*/
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if(!$entity instanceof DeliveryAddress){
return;
}
$this->addNameToUser($args);
$this->addPostalToUser($args);
}
/**
* @param LifecycleEventArgs $args
*/
public function preUpdate(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if(!$entity instanceof DeliveryAddress){
return;
}
$this->addPostalToUser($args);
}
/**
* @param LifecycleEventArgs $args
*/
public function addNameToUser(LifecycleEventArgs $args)
{
/** @var DeliveryAddress $deliveryAdress */
$deliveryAdress = $args->getEntity();
$user = $deliveryAdress->getOwner();
if(empty($user->getFirstName())) $user->setFirstName($deliveryAdress->getFirstName());
if(empty($user->getLastName())) $user->setLastName($deliveryAdress->getLastName());
}
/**
* @param LifecycleEventArgs $args
*/
public function addPostalToUser(LifecycleEventArgs $args)
{
/** @var DeliveryAddress $deliveryAdress */
$deliveryAdress = $args->getEntity();
$user = $deliveryAdress->getOwner();
$user->setPostalCode($deliveryAdress->getZipCode());
}
}
service.yml:
delivery_address.listener:
class: FM\AppBundle\EventListener\DeliveryAddressListener
tags:
- { name: doctrine.event_listener, event: prePersist }
- { name: doctrine.event_listener, event: preUpdate }
prePersist工作正常。但是preUpdate并没有持久存在。
当我在 addPostalToUser()函数中添加此代码时,我的nginx服务器崩溃了:
$args->getEntityManager()->persist($deliveryAdress);
$args->getEntityManager()->flush();
答案 0 :(得分:0)
您的问题是在此事件中不允许更改已更新实体的关联。因此,更改DeliveryAddress上的用户关联将无效。
你可以使用onFlush listener来做这件事 - 这是一个更多的工作,但会做你想要的。