在 SonataAdminBundle 发送有关编辑的电子邮件

Sending an email on edit at SonataAdminBundle

所以在我的 UsersAdmin 中,如果我确认他的帐户,我想向该用户发送一封电子邮件。(在我的例子中,使 Enabled = true)。我在 configureListFields 函数

中执行此操作
/**
     * {@inheritdoc}
     */
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
            ->addIdentifier('username')
            ->add('email')
            ->add('groups')
            ->add('enabled', null, array('editable' => true)) //here
            ->add('locked', null, array('editable' => true))
            ->add('createdAt')
        ;
    }

通过阅读文档我认为我需要使用 batchAction 函数是吗?所以我做了这个:

public function getBatchActions()
{
    // retrieve the default batch actions (currently only delete)
    $actions = parent::getBatchActions();
    $container = $this->getConfigurationPool()->getContainer();
    $user = //how to get the user that i am editing right now?

    if ($this->hasRoute('edit') && $this->isGranted('EDIT')) {
        $body = $container->get('templating')->render('MpShopBundle:Registration:registrationEmail.html.twig', array('user'=> $user));

        $message = Swift_message::newInstance();
        $message->setSubject($container->get('translator')->trans('registration.successful'))
            ->setFrom($container->getParameter('customer.care.email.sender'))
            ->setTo('email@contact.lt')
            ->setBody($body, 'text/html');
        $container->get('mailer')->send($message);

    }

    return $actions;
}

现在我对这个函数有两个不清楚的地方:

  1. 如何获取我要编辑的当前用户数据帽?

  2. 我的方向是否正确?我是否需要覆盖编辑或其他功能?

解决方案

最好的方法是在 postUpdate 事件中进行登录,这样每次更新对象时它都会启动您想要的功能。

public function postUpdate($user)
{
    if($user->getEnabled() == true) {

        $container = $this->getConfigurationPool()->getContainer();

        $body = $container->get('templating')->render('MpShopBundle:Registration:registrationEmail.html.twig', array('user' => $user));

        $message = Swift_message::newInstance();
        $message->setSubject($container->get('translator')->trans('registration.successful'))
            ->setFrom($container->getParameter('customer.care.email.sender'))
            ->setTo('email@contact.lt')
            ->setBody($body, 'text/html');
        $container->get('mailer')->send($message);
    }
}

你可以使用Saving hooks.

   public function postUpdate($user)
    {
       //code to check if enabled 
       // code to send email    
    }