I am submitting a form to a different controller than the one outputting the form.
My question is how do you check the submitted data is valid?
I have tried several things. the main thing I want to validate is "_token"
How do I do this?
This is a sample of my code.
/*
Out put the search form
*/
public function searchAction(Request $request)
{
$form = $this->createFormBuilder()
->setAction($this->generateUrl('email_search')) # <- route to the search process controler
->setMethod('GET')
->add('userSearch', 'text',array(
'required' => true,
'label' => false,
'attr' => array(
'placeholder' => 'Search User Email',
)
)
)
->add('Serch', 'submit')
->getForm();
return $this->render(
'TwigBundle:Search:Search.html.twig',
array(
'form' => $form->createView( )
)
);
}
/*
Process the search
*/
public function emailResultsAction(Request $request){
$form = $this->createFormBuilder()->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$ret = $_POST;
}else{
$ret = 'failed';
}
/*
... Process the search
*/
return new Response(print_r($ret));
}
This gives the error:
"Call to undefined function Acmy\UserBundle\Controller\getForm() in xxxxxxx"
I can validate the search myself but I do not know how to validate the _token.
This does not seem to be covered in the Symfony2 documentation.
Thanks in advance.
Separate your form creation into it's own form class http://symfony.com/doc/current/book/forms.html#creating-form-classes.
By doing this, you can just create the form in your second method/ controller and then bind the request to the form using handleRequest, then check if the form is valid by doing
if ($form->isValid()){...
You can create a method in your controller which creates your form, and then use that to get the Form class from both of the actions.
Pseudo:
private function buildSearchForm() {
return $this->createFormBuilder()
->setAction(...)
// ...
}
public function searchAction(Request $request) {
$form = $this->buildSearchForm();
// Do the necessary things
}
public function emailResultsAction(Request $request) {
$form = $this->buildSearchForm();
// Do your validation here
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With