Search code examples
angularjsformssymfonypayloadngresource

symfony2 form how to accept json payload from angular resource


I'm currently trying to combine a Symfony Form with angularJS... A Service posts data to a form, that should save an entity to the database. Unfortunately, ngResource sends the data as a JSON payload, so that Symfony Forms can't process it... I tried many things on angular side, like changing the headers:

headers : {'Content-Type': 'application/x-www-form-urlencoded'}

I couldn't find much more on angular side, so I thought that I could find a Solution on Symfony Side. Any Idea how I could get this to work? Angular-Solutions are welcome too of course.


Solution

  • I finally found a solution, after reading deeper in the documentation. Symfony\Component\Form\Form::bind doesn't require a Request, it works with an array too. so here's my Solution (the sloppy way, would need some checking of the header, etc. for production use..)

    public function setFooAction(Request $request){
    
      $form = $this->createForm();//get the form class, etc...
      $json_data = json_decode($request->getContent(),true);//get the response data as array
      $form->bind($json_data); //Bind data to Form
    
      if ($form->isValid()) {
        ...
    
      }
    
    }