简体   繁体   中英

Sending an email on edit at SonataAdminBundle

So in my UsersAdmin I want to send an email to that user if I confirm his account.(in my case, making Enabled = true ). I do this in the configureListFields function

/**
     * {@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')
        ;
    }

By reading the documentation I think i need to use the batchAction function yes? So I made this:

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;
}

Now I am stuck with two unclear thing with this function:

  1. How can I get the current user data hat I want to edit?

  2. Am I even going in the right direction? Do I need to override edit or maybe some other function?

THE SOLUTION

The best way is to do your login in the postUpdate event, so that everytime you update an object it initiates the functions you want.

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);
    }
}

you can use Saving hooks.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM