Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }

    // ...
}

What i'm doing wrong? :/ Thanks!

like image 695
coolfarmer Avatar asked Dec 02 '22 09:12

coolfarmer


2 Answers

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"}}
 * )
like image 135
Winzza Avatar answered Dec 04 '22 01:12

Winzza


Are you under PHP 7.0 or above? In PHP 7.1 you can have nullable return types for functions, so your

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

With the ? before \DateTime, the function will return null as well.

like image 24
Marius S Avatar answered Dec 04 '22 01:12

Marius S