我正在使用stof Doctrine扩展的symfony 2.6.3。
TimeStampable和SoftDeletable可以很好地工作。
同样可责怪的“在创建时”和“在更新时”也能很好地工作:
/**
* @var User $createdBy
*
* @Gedmo\Blameable(on="create")
* @ORM\ManyToOne(targetEntity="my\TestBundle\Entity\User")
* @ORM\JoinColumn(name="createdBy", referencedColumnName="id")
*/
protected $createdBy;
/**
* @var User $updatedBy
*
* @Gedmo\Blameable(on="update")
* @ORM\ManyToOne(targetEntity="my\TestBundle\Entity\User")
* @ORM\JoinColumn(name="updatedBy", referencedColumnName="id")
*/
protected $updatedBy;
但是“不断变化”似乎行不通。
/**
* @var User $deletedBy
*
* @Gedmo\Blameable(on="change", field="deletedAt")
* @ORM\ManyToOne(targetEntity="my\UserBundle\Entity\User")
* @ORM\JoinColumn(name="deletedBy", referencedColumnName="id")
*/
protected $deletedBy;
我在“deletedAt”字段上配置了SoftDeletable。 SoftDeletable可以正常工作,但是从未填充
deletedBy
。我如何设法使其正常工作?我只想设置删除该实体的用户ID。
最佳答案
class SoftDeleteListener
{
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
/**
* Method called before "soft delete" system happened.
*
* @param LifecycleEventArgs $lifeCycleEvent Event details.
*/
public function preSoftDelete(LifecycleEventArgs $lifeCycleEvent)
{
$document = $lifeCycleEvent->getDocument();
if ($document instanceof SoftDeletedByInterface) {
$token = $this->tokenStorage->getToken();
if (is_object($token)) {
$oldValue = $document->getDeletedBy();
$user = $token->getUser();
$document->setDeletedBy($user);
$uow = $lifeCycleEvent->getObjectManager()->getUnitOfWork();
$uow->propertyChanged($document, 'deletedBy', $oldValue, $user);
$uow->scheduleExtraUpdate($document, array('deletedBy' => array($oldValue, $user)));
}
}
}
}