<?php
namespace App\Controller;
use App\Form\UserType;
use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Doctrine\Persistence\ManagerRegistry;
class RegistrationController extends AbstractController
{
/**
* @Route("/register", name="user_registration")
*/
public function register(Request $request, UserPasswordHasherInterface $passwordHasher, ManagerRegistry $managerRegistry)
{
$entityManager = $managerRegistry->getManager();
// 1) build the form
$user = new User();
$form = $this->createForm(UserType::class, $user);
// 2) handle the submit (will only happen on POST)
$form->handleRequest($request);
if ($form->isSubmitted()) {
// 3) Encode the password (you could also do this via Doctrine listener)
$plaintextPassword = $form->get('plainPassword')->getData();
// hash the password (based on the security.yaml config for the $user class)
$hashedPassword = $passwordHasher->hashPassword(
$user,
$plaintextPassword
);
$user->setPassword($hashedPassword);
// 4) save the User!
$entityManager->persist($user);
$entityManager->flush();
// ... do any other work - like sending them an email, etc
// maybe set a "flash" success message for the user
return $this->redirectToRoute('app_login');
}
return $this->render(
'registration/register.html.twig',
array('form' => $form->createView())
);
}
}