Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handleRequest($request) does not work for "GET" method in Symfony 2

Tags:

get

symfony

I am a noobie in Symfony2. The handleRequest() function does not work for "GET" method whereas same code works fine for "POST".

public function addAction(Request $request){
    $std = new Student();

    $form = $this->createForm(new StudentForm, $std, 
        array( 'method'=>'GET'));

    $form->handleRequest($request);

    if($form->isSubmitted()){
        $std= $form->getData();
        $em= $this->getDoctrine()->getManager();
        $em->persist($std);
        $em->flush();
        return $this->render('target.twig');
    }

    return $this->render('target twig', 
        array('newStdForm'=> $form->createView(),));
}

The above code is not working but if I change 'method':'GET' to 'method':'POST', then it works fine.

like image 506
Swass Avatar asked Nov 23 '13 07:11

Swass


2 Answers

Specify the form's method in the StudentForm class's buildForm method. Therefore, handleRequest will be able to grab the GET parameters.

class StudentForm
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
         // ...
        $builder->setMethod('GET');
    }
}
like image 57
Pierre Rolland Avatar answered Oct 21 '22 15:10

Pierre Rolland


I think it is because in POST requests, parameters are passed in the body of the HTTP request. And that handleRequest looks for those values inside the body of the request. But in a GET request, parameters are passed in the url directly. So I think that is why the handling doesn't work.

Usually we use GET to fetch a page or url and a POST to send info to server.

like image 1
Lunfel Avatar answered Oct 21 '22 13:10

Lunfel