siwymilek
siwymilek

Reputation: 815

Can't understand how form validation works in symfony

I read a part of documentation about validating a form and still unable to understand how form validation works.

I try to validate requested data by form, but there's no errors.

I want to validate password confirmation, so i am using following code in my UserType.php:

$builder
        ->add('username')
        ->add('password', RepeatedType::class, [
            'first_name' => 'password',
            'second_name' => 'password_confirmation',
            'required' => true,
            'invalid_message' => 'The password fields must match.'
        ]);

So next I try to validate my form data in the following way:

$user = $userManager->createUser();
$form = $this->createForm(UserType::class, $user, ['method' => 'POST']);
$form->submit($request->request->all());

$form->isValid(); // return true
$form->getErrors(); // return no errors

Edit: Problem resolved. I had badly configured FOSRestBundle

Upvotes: 1

Views: 95

Answers (1)

KevinTheGreat
KevinTheGreat

Reputation: 634

 $form->isValid() 

is a function that doesn't validate the form but rather does a series of task you give it if the form is valid. So when a user submits the form, what needs to happen with the data

example:

   if($form->isValid()){
        $em=$this->getDoctrine()->getManager();
        $user->setFirstName($data['firstname']) // use name of field
        $em->persist($user);

        $em->flush();

        return $this->redirectToRoute('your_route', array(
            'needed variable'=> $user_id
        ));
    }

So what you mainly do is take the data from the symfony form and store it in your datebase, you can and then redirect to a new webpage you wish the user to land on. You can also add addflash() messages to show that it either worked or not.

Upvotes: 2

Related Questions