Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Submitting a form to a different controller and check isValid()

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.

like image 682
Joe Avatar asked Oct 16 '13 09:10

Joe


2 Answers

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()){...
like image 52
Mark Avatar answered Nov 15 '22 03:11

Mark


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
}
like image 4
TheOnly92 Avatar answered Nov 15 '22 03:11

TheOnly92