I want to update entity with 'PATCH' method (update only those fields which have been submitted).
/* Edit an existing Content entity.
*
* @Rest\Patch(
* "/{content}.{_format}",
* requirements={"content" = "\d+"},
* defaults = { "_format" = "json" }
* )
*
* @Rest\View(serializerGroups={"user""admin"})
* @param Content $content
* @return View
* @throws \NotFoundHttpException*
*
* @ApiDoc(
* resource="/api/content/",
* description="Updates content data",
*
* input="ContentBundle\Form\ContentType",
*
* output={
* "class"="EntriesBundle\Entity\Content",
* "parsers"={"Nelmio\ApiDocBundle\Parser\JmsMetadataParser"},
* "groups"={"user","admin"}
* }
* )
*/
public function editAction(Request $request, Content $content)
{
if (!$content) {
throw $this-createNotFoundException();
}
$editForm = $this-createForm('ContentBundle\Form\ContentType', $content);
$editForm-submit($request-request-get($editForm-getName()));
$view = View::create()
-setSerializationContext(SerializationContext::create()-setGroups(['user']));
if ($editForm-isSubmitted() && $editForm-isValid()) {
$em = $this-getDoctrine()-getManager();
$em-persist($content);
$em-flush();
$view
-setStatusCode(Codes::HTTP_OK)
-setTemplate("ContentBundle:content:show.html.twig")
-setTemplateVar('contents')
-setData($content);
} else {
$view
-setStatusCode(Codes::HTTP_BAD_REQUEST)
-setTemplateVar('error')
-setData($editForm)
-setTemplateData(['message' = $editForm-getErrors(true)])
-setTemplate('ContentBundle:content:show.html.twig');
}
return $this-get('fos_rest.view_handler')-handle($view);
}
Form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class)
->add('description', TextareaType::class)
->add('eng', CheckboxType::class, [
'required' => false
]);
}
I have entity with 'eng' set to TRUE
.
If I run query to update only title
field, eng
changes to false
. and description
to null. Any ideas why?
I've got it to works.
Remember folks that if you want to use PATCH
method you need to use TextType
instead of ChoiceType
in your form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', TextType::class)
->add('description', TextareaType::class)
->add('eng', TextType::class);
}