Because i am used to Laravel I tried validating forms within a seperate method. But I don't know how to redirect back and display the errors. The main problem is displaying the errors. Best case scenario would be if i can set the errors from the validation method and let the default form error rendering in Symfony take over.
I could be completely wrong with my approach, if so I hope someone could guide me in the right direction.
I made a method to create the form and render it in twig
/**
* @Route("/form")
* @Template("Bundle::form.html.twig")
* @Method("GET")
*/
public function formAction(Request $request)
{
$state = new State();
$form = $this->createFormBuilder($state)
->add('name', TextType::class)
->add('save', SubmitType::class, array('label' => 'Submit'))
->getForm();
return [
'form' => $form->createView(),
];
}
And another method to validate the form and redirect back on error
/**
* @Route("/form")
* @Method("POST")
*/
public function formAction(Request $request)
{
$state = new State();
$form = $this->createFormBuilder($state)
->add('name', TextType::class)
->add('save', SubmitType::class, array('label' => 'Submit'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted()) {
if (!$form->isValid()) {
// How to pass errors?
return $this->redirectTo('/form');
}
// ... Store State
}
// ...
}
1) Check this out
2) if you really want to add an error from your controller:
use Symfony\Component\Form\FormError;
// ...
$form->get('name')->addError(new FormError('Wrong name you fool :p'));