Search code examples
jsonsymfonyfosrestbundle

SF remove unwanted json input with ParamConverter


Is that possible to use ParamConverter with json input and remove unwanted fields ?

In my entity Folder, i have the fields name (string) and createdAt (Datetime). I don't want the use who send a new Folder choose the value of createdAt.

json input:

{
  "name": "F name",
  "createdAt": "01/02/03"
}

Should save the entity only with the name.

How can i ignore the field createAt (or any unwanted input) ?

/**
 * @Rest\Post("/folder")
 * @Rest\View(StatusCode = 201)
 * @ParamConverter(
 *     "folder",
 *     converter="fos_rest.request_body",
 *     options={
 *        "validator"={ "groups"="Create" }
 *     }
 * )
 *
 */
public function createAction(Folder $folder, ConstraintViolationList $violations)
{
    if (count($violations)) {
        return $this->view($violations, Response::HTTP_BAD_REQUEST);
    }

    $em = $this->getDoctrine()->getManager();
    $em->persist($folder);
    $em->flush();

    return $folder;
}

Solution

  • I did it !

    I use the JmsSerializer groups.

    /**
     * @Rest\Post("/folder")
     * @Rest\View(StatusCode = 201)
     * @ParamConverter(
     *     "folder",
     *     converter="fos_rest.request_body",
     *     options={
     *        "validator"={ "groups"="create" },
     *        "deserializationContext"={"groups"={"folder_create"}}
     *     }
     * )
     *
     */