src/Controller/RegistrationController.php line 17

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Form\UserType;
  4. use App\Entity\User;
  5. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  9. use Doctrine\Persistence\ManagerRegistry;
  10. class RegistrationController extends AbstractController
  11. {
  12.     /**
  13.      * @Route("/register", name="user_registration")
  14.      */
  15.     public function register(Request $requestUserPasswordHasherInterface $passwordHasherManagerRegistry $managerRegistry)
  16.     {
  17.         $entityManager $managerRegistry->getManager();
  18.         // 1) build the form
  19.         $user = new User();
  20.         $form $this->createForm(UserType::class, $user);
  21.         // 2) handle the submit (will only happen on POST)
  22.         $form->handleRequest($request);
  23.         if ($form->isSubmitted()) {
  24.             // 3) Encode the password (you could also do this via Doctrine listener)
  25.             $plaintextPassword $form->get('plainPassword')->getData();
  26.             // hash the password (based on the security.yaml config for the $user class)
  27.             $hashedPassword $passwordHasher->hashPassword(
  28.                 $user,
  29.                 $plaintextPassword
  30.             );
  31.             $user->setPassword($hashedPassword);
  32.             // 4) save the User!
  33.             $entityManager->persist($user);
  34.             $entityManager->flush();
  35.             // ... do any other work - like sending them an email, etc
  36.             // maybe set a "flash" success message for the user
  37.             return $this->redirectToRoute('app_login');
  38.         }
  39.         return $this->render(
  40.             'registration/register.html.twig',
  41.             array('form' => $form->createView())
  42.         );
  43.     }
  44. }