Learn how to register an user with fosuserbundle in any controller (manually without default forms) in symfony.

If you need to register an user manually (without forms) in a custom controller in symfony 2 or 3 you only need to have access to theĀ fos_user.user_manager service in your controller.

You'll be asking yourself, why not simply persist an user entity directly with doctrine ? And the answer is pretty simple, we don't want to handle by our own the encryption stuff which is already implemented in FOSUserBundle. That's why we need to get access to the service, to use the setPlainPassword method.

Note: If you're not implementing the insertion of an user manually from a controller, you will need to inject the container in order to retrieve the fos_user service from wherever you are.

Insertion example

class MyCustomuserController extends Controller
{
   public function registeruserAction(Request $request){
       $succesfullyRegistered = $this->register("[email protected]","demoUsername","demoPassword");

       if($succesfullyRegistered){
           // the user is now registered !
       }else{
           // the user exists already !
       }
   }
 
   /**
    * This method registers an user in the database manually.
    *
    * @return boolean User registered / not registered
    **/
   private function register($email,$username,$password){    
      $userManager = $this->get('fos_user.user_manager');

      // Or you can use the doctrine entity manager if you want instead the fosuser manager
      // to find 
      //$em = $this->getDoctrine()->getManager();
      //$usersRepository = $em->getRepository("mybundleuserBundle:User");
      // or use directly the namespace and the name of the class 
      // $usersRepository = $em->getRepository("mybundle\userBundle\Entity\User");
      //$email_exist = $usersRepository->findOneBy(array('email' => $email));
      
      $email_exist = $userManager->findUserByEmail($email);

      // Check if the user exists to prevent Integrity constraint violation error in the insertion
      if($email_exist){
          return false;
      }

      $user = $userManager->createUser();
      $user->setUsername($username);
      $user->setEmail($email);
      $user->setEmailCanonical($email);
      $user->setLocked(0); // don't lock the user
      $user->setEnabled(1); // enable the user or enable it later with a confirmation token in the email
      // this method will encrypt the password with the default settings :)
      $user->setPlainPassword($password);
      $userManager->updateUser($user);

      return true;
   }
}

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors