Reputation: 570
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?
Upvotes: 2
Views: 3155
Reputation: 5701
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"
Upvotes: 2
Reputation: 7183
There are two solutions:
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);
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.
Upvotes: 1
Reputation: 13485
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));
Upvotes: 4