Search code examples
formssymfonysymfony4

How to send flash message to form error field (Symfony)


This is my registration form code:

public function register(Request $request, UserPasswordEncoderInterface $passwordEncoder)
{
    $user = new User();
    $form = $this->createForm(RegisterType::class, $user);

    $form->handleRequest($request);
    if ($form->isSubmitted() && $form->isValid()) {

        $password = $passwordEncoder->encodePassword($user, $user->getPlainPassword());
        $user->setPassword($password);
        $user->setPlan('1');
        $datetime = new \DateTime();
        $datetime->modify('+30 day');
        $user->setExpiration($datetime);
        $user->setActive('0');

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($user);
        $entityManager->flush();

        $this->addFlash('success', 'Your account has been created. Check your inbox for verification e-mail.');
    }

    return $this->render('home/register.html.twig', array(
        'form' => $form->createView(),
    ));
}

At the end of saving user into database there's set Flash message. Is there any way of showing that message through form error field?


Solution

  • No you cannot add a flash message to a form's errors. The only way to manipulate the errors of a form through it's class API is the public function addError(FormError $error) but as you can see it's only accepts arguments of type FormError not strings.