Aurel
Aurel

Reputation: 796

FOSUserBundle : get repository from inside FormHandler

I need to set a default value to a new user before saving it. The problem is that I can't find a way to get an object through its repository from inside the FormHandler.

<?php
namespace Acme\UserBundle\Form\Handler;

use FOS\UserBundle\Form\Handler\RegistrationFormHandler as BaseHandler;
use FOS\UserBundle\Model\UserInterface;

class RegistrationFormHandler extends BaseHandler
{

    protected function onSuccess(UserInterface $user, $confirmation)
    {
        $repository = $this->container->get('doctrine')->getEntityManager()->getRepository('AcmeUserBundle:Photo');
        if($user->isMale()){
            $photo = $repository->getDefaultForMale();
            $user->setPhoto($photo);
        }
        else {
            $photo = $repository->getDefaultForFemale();
            $user->setPhoto($photo);
        }

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

The problem comes from the following line :

$repository = $this->container->get('doctrine')->getEntityManager()->getRepository('AcmeUserBundle:Photo');

... and I can't find a way to get this repository, or the entity manager from this FormHandler.

Many thanks for your help ! A

Upvotes: 1

Views: 2453

Answers (2)

Mun Mun Das
Mun Mun Das

Reputation: 15002

You have to define a service that reference your extended handler class and point it in app/config.yml. e.g

The class,

//namespace definitions
class MyHandler extends RegistrationFormHandler{

    private $container;

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

    protected function onSuccess(UserInterface $user, $confirmation)
    {
        $repository = $this->container->get('doctrine')->getEntityManager()->getRepository('AcmeUserBundle:Photo');

        // your code

    }

The service,

 my.registration.form.handler:
    scope: request
    class: FQCN\Of\MyHandler
    arguments: [@fos_user.registration.form, @request, @fos_user.user_manager, @fos_user.mailer, @service_container]

Lastly in app/config.yml,

fos_user:
    #....
    registration:
      #...
      form:
        handler: my.registration.form.handler

Upvotes: 4

Max Małecki
Max Małecki

Reputation: 1702

FOS got his own UserManager. Try to use this.

Upvotes: -1

Related Questions