Reputation: 343
I have an issue with Symfony 2.6 form collections. Removing elements from collection works, however only when at least one is present. If the last element is removed from DOM (leaving the collection container empty), no elements are removed from the collection after handling request.
Example:
I have a form with collection "children" and two children, "a" and "b". I remove the child "b" from DOM, save, removeChild is called, the child is removed. Now I also remove child "a", save, nothing happens - after refreshing the form the child is still present. When dumping the main entity after the form has handled request, the child is present in it's collection as well.
Did anyone have similar problem and found a solution?
Upvotes: 3
Views: 574
Reputation: 1060
You can delete all the items of a Collection of an Entity simply by:
$request['collectionName'] = null; //or empty array
$form->submit($request, false);
Problems arise when this $request comes from a javascript Ajax call:
var item = {field: 'test', collectionName: null};
ajaxPatchRequest(item);
since the null value is received as String "null". If collectionName is an empty array it will not be passed within the ajax call. Thus, use the null value and apply a preprocessing before $form->submit():
$toPatch = array();
foreach($request->request->all() as $key => $value) {
if($value === 'null') {
$toPatch[$key] = null;
} else {
$toPatch[$key] = $value;
}
}
$form->submit($toPatch, false);
Upvotes: 0
Reputation: 343
Thanks to @Daniel pointing me in a new direction I have found a solution. The method submit does in fact accept second argument - clear empty. Passing request to submit is however deprecated and will be removed in Symfony 3.0. Handle request does in fact support the clear empty feature. It is simply not passed manually, but based on the request method. If the method is post, clear empty is set to true. If method is patch, clear empty is false. In my case the method was patch, hence the issue.
Upvotes: 3
Reputation: 290
You can do this by 2 methods :
But don't forget cascade={"remove"}
annotation
Upvotes: 0