Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

API Platform error with not nullable field

I have a simple entity

 /**
 * @var string|null
 *
 * @ORM\Column(name="city", type="string", length=255, nullable=false)
 * @Assert\NotNull()
 */
private $city;

 ...

  /**
 * @param string|null $city
 * @return CustomerAddressList
 */
public function setCity(?string $city): CustomerAddressList
{
    $this->city = $city;
    return $this;
}

If I try to pass null to the field city the result is a runtime exception instead of a validation error:

{
  "@context": "/api/v2/contexts/Error",
  "@type": "hydra:Error",
  "hydra:title": "An error occurred",
  "hydra:description": "The type of the address attribute must be string, NULL given."
}

If I change nullable=false to true then everything works fine, but it's not an acceptable solution.

How can I fix it?

like image 462
PGLongo Avatar asked Feb 15 '26 17:02

PGLongo


1 Answers

Found the solution.

* @ApiResource(
*     denormalizationContext={"disable_type_enforcement"=false}
* )

Adding the denormalizationContext with "disable_type_enforcement"=false disable the validation of the request using Doctrine annotations.

{
    "@context": "/api/v2/contexts/ConstraintViolationList",
    "@type": "ConstraintViolationList",
    "hydra:title": "An error occurred",
    "hydra:description": "city: This value should be not null",
    "violations": [
    {
    "propertyPath": ".city",
    "message": "This value should be not null."
},

If it's necessary to enforce the field to be of a specific type then it's necessary to add the proper @Assert\Type(...) as prior Symfony 4.3

like image 113
PGLongo Avatar answered Feb 20 '26 08:02

PGLongo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!