How to assert not null subresource in Api-Platform?

Viewed 710

I have 2 entities:

class Act 
{
    /**
     * @Assert\Count(min=1)
     * @Assert\Valid(traverse=true)
     * @ORM\OneToMany(targetEntity="App\Entity\ActItem", mappedBy="act", cascade={"persist"})
     */
    private $items;
}

class ActItem 
{
    /**
     * @ORM\ManyToOne(targetEntity="App\Entity\Act", inversedBy="items")
     * @ORM\JoinColumn(nullable=false)
     */
    private $act;

    /**
     * @Assert\NotNull
     * @Assert\Type("float")
     *
     * @ORM\Column(type="float")
     */
    private $count;
}

ActItem has Assert\NotNull, but when I try to create/update act with item like {count: null} then I get response:

hydra:description: "The type of the "count" attribute must be "float", "NULL" given."

I notice that if I remove @ORM\Column(type="float") then I get:

hydra:description: "items[0].count: This value should not be blank."

So why it working like this? How can i make it work in another order?

1 Answers

I had this exact problem some time ago, apparently this is because your doctrine field is set as not nullable. (@Assert\Type("float"))

During runtime api-platform checks your Doctrine metadata and throws InvalidArgumentException if your data doesn't fit the criteria. (I don't like this "feature" either, not sure why they're doing it).

To "fix" this you change your field to @ORM\Column("float", nullable=true)

It is also possible to override api_platform.doctrine.orm.metadata.property.metadata_factory service and change its behavior to ignore doctrine nullable.

Related