如何正确嵌入注册表以便我可以通过FosUserBundle进行电子邮件确认?

时间:2013-02-06 09:25:24

标签: symfony symfony-2.1 fosuserbundle

我有一个Artist实体和一个简单的用户实体。

我的网站上可以注册2个:一个用于艺术家,一个用于简单用户。 一切都很好用户,他收到一封确认电子邮件等。它很棒,但这一次,当艺术家在我的网站上注册时(我嵌入了FosUserBundle的UserType,以便艺术家也在我的网站上注册为用户),电子邮件确认检查输入的电子邮件的有效性,然后启用用户不像简单用户那样发送。

我知道这不会发生,因为要求艺术家注册的动作不是FosUserBundle的RegistrationController的registerAction,而是我的动作我的ArtistController的newAction。

所以我尝试使用RegistrationController和RegistrationFormHandler的一些代码,但是我无法使用它,因为我没有设法使用例如ArtistHandler中的邮件程序接口和令牌生成器:

这是我的ArtistHander.php

<?php

namespace My\Bundle\BrocBundle\Form;

use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;

use My\Bundle\BrocBundle\Entity\Artist;

use FOS\UserBundle\Mailer\Mailer;
use FOS\UserBundle\Util\TokenGenerator;

class ArtistHandler
{
    protected $form;
    protected $request;
    protected $em;

    public function __construct(Form $form, Request $request, EntityManager $em, Mailer $mailer, TokenGenerator $tokenGenerator)
    {
        $this->form = $form;
        $this->request = $request;
        $this->em = $em;
        $this->mailer = $mailer;
        $this->tokenGenerator = $tokenGenerator;
    }

    public function process()
    {
        if ($this->request->getMethod() == 'POST') 
        {
            $this->form->bindRequest($this->request);

            if ($this->form->isValid() ) 
            {
                $this->onSuccess($this->form->getData());
                return true;
            }
        }

        return false;
    }

    public function onSuccess(Artist $artist)
    {

        $user = $artist->getUser();
        $user->setEnabled(false);

        if (null === $user->getConfirmationToken()) 
        {
            $user->setConfirmationToken($this->tokenGenerator->generateToken());
        }

        $this->mailer->sendConfirmationEmailMessage($user);


        $this->userManager->updateUser($user);

        $this->em->persist($artist);
        $this->em->flush();
    }

}

3 个答案:

答案 0 :(得分:2)

如果你想使用邮件程序,你必须注入它,就像你正在使用EntityManager

一样

所以:

  • 在您的service.yml课程中加入ArtistHandler(或相关)注入
  • 修改ArtistHandler contructor

有关详细信息,您还可以访问this page(symfony2文档;不同的方法)

答案 1 :(得分:0)

UPDATE好的,最后这是我所做的但不确定这是最好的方法吗?要做到这一点,如果你们中的一个人认为有更好的方式,我会很乐意这样做而不是这个:

public function newAction()
{
    $em = $this->getDoctrine()->getEntityManager();
    $artist = new Artist();

    $mailer = new Mailer($this->get('mailer'), $this->get('router'), $this->get('templating'), array('confirmation.template'=> 'MyUserBundle:Registration:email.txt.twig', 'from_email' => array('confirmation' => 'mysenderadress@gmail.com')));
    $tokenGenerator = new TokenGenerator;
    $form = $this->createForm(new ArtistType, $artist);
    $formHandler = new ArtistHandler($form, $this->get('request'), $this->getDoctrine()->getEntityManager(), $mailer, $tokenGenerator);

    $confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');


    if ($formHandler->process()) 
    {   

        $authUser = false;
        if ($confirmationEnabled) {
            $this->container->get('session')->set('fos_user_send_confirmation_email/email', $artist->getUser()->getEmail());
            $route = 'fos_user_registration_check_email';
        } else {
            $authUser = true;
            $route = 'fos_user_registration_confirmed';
        }

        $url = $this->container->get('router')->generate($route);
        $response = new RedirectResponse($url);

        if ($authUser) {
            $this->authenticateUser($artist->getUser(), $response);
        }

        return $response;
    }
    return $this->render('MyBrocBundle:Artist:new.html.twig', array('form' => $form->createView()));
}

答案 2 :(得分:0)

我遇到了同样的问题。我用了不同的方法。仔细查看onSuccess

<?php

namespace  UsersBundle\Form\Handler;

use FOS\UserBundle\Form\Handler\RegistrationFormHandler as BaseHandler;
use FOS\UserBundle\Model\UserInterface;
use UsersBundle\Entity\User;
use AdminBundle\EntityDao\EntidadDao;
use AdminBundle\EntityDao\RolDao;
use UsersBundle\EntityDao\UserDao;

class RegistrationFormHandler extends BaseHandler{
    private $auditUser;
    private $entId;
    private $userInterno;

    private $container;

    public function __construct($form, $request, $userManager, $mailer, $container){
        parent::__construct($form, $request, $userManager, $mailer);
        $this->container = $container;
    }

    public function processIns($entId, $userInterno, $auditUserIns, $confirmation = false){
        $this->auditUser = $auditUserIns;
        $this->entId = $entId;
        $this->userInterno = $userInterno;

        return $this->process($confirmation);
    }

    /*public function processUpd($confirmation = false, $auditUserUpd){
        $this->auditUserUpd = $auditUserUpd;
        return $this->process($confirmation);
    }*/

    public function process($confirmation = false){
        $user = $this->userManager->createUser();
        $this->form->setData($user);

        if ('POST' == $this->request->getMethod()) {
            $this->form->bindRequest($this->request);

            if ($this->form->isValid()) {

                $tmp = $user->getIdUsuario();


                //Si es update
                if(empty($tmp) ){
                    $user->setAuditUserIns($this->auditUser);
                    $user->setAuditDateIns(new \DateTime());

                    $tmp = $this->entId;
                    if( !empty($tmp)){
                        $entidadDao = new EntidadDao($this->container->get("doctrine"));
                        $entidad = $entidadDao->getEntidad($this->entId);
                        $user->setEntidad($entidad);
                    }

                //Si es Insert    
                }else{
                    $userDao = new UserDao($this->container->get("doctrine"));

                    //Se obtiene el registro de la BD
                    $tmp = $userDao->getUserEspecifico($user->getIdUsuario());

                    //Se le asigna al Formulario
                    $this->form->setData($tmp);

                    //Se realiza un merge con lo que se envio en el Request
                    $this->form->bindRequest($this->request);

                    $user = $tmp;
                    $tmp->setAuditUserUpd($this->auditUser);
                    $tmp->setAuditDateUpd(new \DateTime());
                }

                $rolDao= new RolDao($this->container->get("doctrine"));

                //Se asignan roles dependiendo del usuario interno
                if($this->userInterno =='false'){
                    $user->setRols($rolDao->getRolesEspecificos(
                            $user->getEntidad()->getEntImportador(),
                            $user->getEntidad()->getEntProductor(),
                            $user->getEntidad()->getEntComprador(),
                            $user->getEntidad()->getEntCompVend(),
                            $user->getUserTipo(),
                            $user->getUserInterno(),
                            $user->getUserInternoTipo()
                    ));
                }else{
                    $user->setRols($rolDao->getRolesEspecificos(
                            false,
                            false,
                            false,
                            false,
                            $user->getUserTipo(),
                            $user->getUserInterno(),
                            $user->getUserInternoTipo()
                    ));
                }


                //Hacer busqueda de los roles segun los campos de tipos y obtener el listado de objetos.
                $this->onSuccess($user, $confirmation);
                // do your custom logic here
                return true;
            }
        }

        return false;
    }

    protected function onSuccess(UserInterface $user, $confirmation){
        // Note: if you plan on modifying the user then do it before calling the 
        // parent method as the parent method will flush the changes

        //parent::onSuccess($user, $confirmation);

        if ($confirmation) {
            $user->setEnabled(false);
            $user->generateConfirmationToken();
            $this->mailer->sendConfirmationEmailMessage($user);
        } else {
            $user->setConfirmationToken(null);
            $user->setEnabled(true);
        }

        $this->userManager->updateUser($user);

        // otherwise add your functionality here
    }
}