Search code examples
phpsymfonyapi-platform.com

Allowing NULL value in json with API-Platform


I have currently this entity and I want to show my property firedDate in my JSON even is the value is null.

/**
 * @ApiResource(normalizationContext={"groups"={"employee"}})
 * @ApiFilter(DateFilter::class, properties={"dateProperty": DateFilter::INCLUDE_NULL_BEFORE_AND_AFTER})
 * @ORM\Table(name="employee")
 */
class Employee
{
    // ...
    
    /**
     * @ORM\Column(type="datetime", nullable=true)
     * @Groups({"employee"})
     */
    private $firedDate;


    public function getFiredDate(): ?\DateTimeInterface
    {
        return $this->firedDate;
    }

    // ...
}

Currently, when the value is null, it's not shown in the response.


Solution

  • I think I found the right solution to this problem. Set skip_null_values in false in your normalizationContext:

     * @ApiResource(
     *     itemOperations={
     *         "get" = {
     *             //...
     *         }
     *         "put" = {
     *             //...
     *         },
     *         "patch" = {
     *             //...
     *         }
     *     },
     *     collectionOperations={
     *         "get",
     *         "post" = {
     *             //...
     *         }
     *     },
     *     normalizationContext={
     *         "skip_null_values" = false,
     *         "groups" = {"object:read"}
     *     },
     *     denormalizationContext={"groups" = {"object:write"}}
     * )