嗨,我正在尝试在此文档之后进行Symfony事件侦听器:http://symfony.com/doc/2.8/cookbook/doctrine/event_listeners_subscribers.html
<?php
namespace FMAppBundleEventListener;
use DoctrineORMEventLifecycleEventArgs;
use FMAdminBundleEntityAddressBillingAddress;
class BillingAdressListener
{
/**
* @param LifecycleEventArgs $args
*/
public function listenBillingAdress(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if(!$entity instanceof BillingAddress){
return;
}
$this->postPersist($args);
}
/**
* @param LifecycleEventArgs $args
*/
public function postPersist(LifecycleEventArgs $args)
{
$em = $args->getEntityManager();
$billingAdress = $args->getEntity();
dump($billingAdress); die();
}
}
service.yml
billing_adress.listener:
class: FMAppBundleEventListenerBillingAdressListener
tags:
- { name: doctrine.event_listener, event: listenBillingAdress }
,但是当我用 BillingAddress 对象提交表单时,什么都没有发生。
我做错了什么?
它在学说中称为实体听众。这是文档。
不要忘记在映射中添加您的实体侦听器。例如XML映射:
<entity name="AppBundleEntityAssignmentAttempt" table="app_assignment_attempt" >
<entity-listeners>
<entity-listener class="AppBundleEntityListenerAssignmentAttemptListener">
<lifecycle-callback type="prePersist" method="prePersist"/>
<lifecycle-callback type="preUpdate" method="preUpdate"/>
</entity-listener>
</entity-listeners>
<!-- Rest mapping -->
</entity>
在配置中您可以简单地添加
app.entity_listener.assignment_attempt:
class: AppBundleEntityListenerAssignmentAttemptListener
tags:
- { name: doctrine.orm.entity_listener }
我不好,我没有做 persist ,而是 update 。
它可以与 persist 一起使用。
现在是我的代码:
<?php
namespace FMAppBundleEventListener;
use DoctrineORMEventLifecycleEventArgs;
use FMAdminBundleEntityAddressBillingAddress;
class BillingAddressListener
{
/**
* @param LifecycleEventArgs $args
*/
public function prePersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
if(!$entity instanceof BillingAddress){
return;
}
$this->addNameToUser($args);
}
/**
* @param LifecycleEventArgs $args
*/
public function addNameToUser(LifecycleEventArgs $args)
{
/** @var BillingAddress $billingAdress */
$billingAdress = $args->getEntity();
$user = $billingAdress->getOwner();
if(empty($user->getFirstName())) $user->setFirstName($billingAdress->getFirstName());
if(empty($user->getLastName())) $user->setLastName($billingAdress->getLastName());
}
}
,我必须称呼预科方法。我当时是相反的。
billing_address.listener:
class: FMAppBundleEventListenerBillingAddressListener
tags:
- { name: doctrine.event_listener, event: prePersist }