1

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
    }

    // ... 
}
Matteo
  • 37,680
  • 11
  • 100
  • 115
finalgamer
  • 13
  • 2
  • In Symfony, displaying, validating and saving a form is normally done in only one action. – Emanuel Oster Oct 12 '16 at 09:21
  • You have the same code twice, except for the `isValid()` part. Do it all in one action. Like here: http://symfony.com/doc/2.8/forms.html#handling-form-submissions – Jared Farrish Oct 12 '16 at 22:36

1 Answers1

0

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'));
Frank B
  • 3,667
  • 1
  • 16
  • 22