2
votes

I've read this article (http://welcometothebundle.com/symfony2-rest-api-the-best-2013-way/) to build my system REST API with Symfony2. Following the guide, i no longer use Symfony2 Form as web form but only 2 main job: map data into Entity and Validation. In my view, i'm using AngularJS to call REST API with the help from its good built-in services.

In my case, I want to update my entity, AngularJS will get JSON data which serialized from entity and set back to $scope.object to bind to form. For example:

{
    email: "[email protected]"
    id: 22
    party: {
        id:24,
        lastName: Gates,
        firstName: Bill
    }
}

Make some change then send $scope.object to update route with PUT method, I will use Symfony2 form and submit this data, but Symfony2 form validation keep throwing exception This form should not contain extra fields.. I know id field is not a form field but don't know how to make Symfony to ignore all these extra fields. Can you help me?

3
The form param name given in Symfony form doesn't match the field name of JSON. Symfony form usually have myform[email] myform[id]. So the form handler won't catch the correct field name but putting those to extra fields. BTW, I'm working in an org developing on top of AngularJS + Symfony2. In our app, When we want to POST /some_url, we use JSON de-serialization provided by JMSSerializerBundle. You can take a look on that :)Marco

3 Answers

4
votes

If the id field is not a form field, then you can add that to your form but add it as a non-mapped field (i.e. it doesn't relate to a property on the entity):

$builder->add('id', 'hidden', array('mapped' => false));
2
votes

From Symfony version 2.6 you can use new form option allow_extra_fields (accepted pull request). 2.6 release is planned on 11/2014 but you can use it already (in composer.json):

"symfony/symfony": "2.6.*@dev"
1
votes

There are two solutions:

  1. You can unset the field id and modify the request data before you pass the data array to the form, so that it fits to your form. In your case I assume it must be:

    $data = $request->request->all(); // get all posted data
    unset($data['id']);
    $data['party'] = $data['party']['id'];
    
    $form->submit($data);
    
  2. You can add the field to your form type or to the form builder and set the mapped-option to false, so that Symfony does not try to map it to your entity. Like @JamesHalsall already mentioned.