Search code examples
symfonysymfony-formssymfony-validator

When to call validator in Symfony forms?


I dont know when to call validation in this situation ? I made some constraints in Form/Model/User.php class for propertys, and don't know where to call it and how.And how to display errors on the same page. What is best practice to do this right ?

public function userRegistrationAction(Request $request) {
$formUser = new FormUser();
$form = $this->createForm(UserType::class, $formUser);
$form->handleRequest($request);

if($form->isSubmitted() && $form->isValid()) {
  $userEntity = new EntityUser();

  $name = $form['name']->getData();
  $surname = $form['surname']->getData();
  $email = $form['email']->getData();
  $password = $this->get('security.password_encoder')
    ->encodePassword($userEntity, $form['password']->getData());
  $now = new\DateTime('now');

  $userEntity->setName($name);
  $userEntity->setSurname($surname);
  $userEntity->setEmail($email);
  $userEntity->setPassword($password);
  $userEntity->setCreated($now);

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

  $request->getSession()
    ->getFlashBag()
    ->add('success', '- Success! ');

   return $this->render('AppBundle:Welcome:homepage.html.twig', array(
     'name' => $name,
     'lastName' => $surname,
   ));
}

Solution

  • OK, this was the problem: 'validation_groups' => ['registration'], i set this group for only one field, now i delete this and working nice, no need for callig validator after isValid.

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'validation_groups' => ['registration'], //delete this 
            'method' => 'post',
            'data_class' => User::class,
            'csrf_protection' => true,
            'cascade_validation' => true
        ));
    }