Handle PATCH action null values with Symfony ParamConverter

435 Views Asked by At

I have a PATCH action in my controller:

/**
 * @ParamConverter("patchRequest", class="array<App\Model\Request\Product\ProductPatchInternalRequest>", converter="fos_rest.request_body")
 * @Patch
 */
public function patchProductsAction(
    array $patchRequest,
    ConstraintViolationListInterface $validationErrors
) {
    if (count($validationErrors) > 0) {
        return $this->view(['errors' => $validationErrors], Response::HTTP_UNPROCESSABLE_ENTITY);
    }

    return $this->successNoContent();
}

ProductPatchInternalRequest model has these attributes: id and brand_id. Now the problem is that brand_id can be passed as null via request and it means that brand_id attribute should be set to null.

Now if my JSON looks like this:

[
    {
        "id": 10
    },
    {
        "id": 11,
        "brand_id": null
    }
]

Then my request object is converted to this array:

array:2 [
  0 => App\Model\Request\Product\ProductPatchInternalRequest {#1770
    #id: 10
    #brandId: null
  }
  1 => App\Model\Request\Product\ProductPatchInternalRequest {#1774
    #id: 11
    #brandId: null
  }
]

As you can see - first array element has brandId as null even if I didnt't passed it on my request. That's because my request object has this parameter.

I'm looking for a solution which allows me to pass only the data I need to patch, but also have a possibility to set any parameter to null.

Is this possible with ParamConverter?

EDIT: One of the solutions could be using Symfony Forms with submit action? Like https://symfonycasts.com/screencast/symfony-rest/patch-programmer

Is this the proper way to do it?

0

There are 0 best solutions below