3

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?

8
  • 1
    Well the nullable attribute is exactly made to make the field accept null values. Why is it not an option to enable it? Commented Jan 8, 2020 at 13:40
  • Because I want the field nullable in the database and if the client makes a mistake and sends null as a value I would like to have a validation error. Commented Jan 8, 2020 at 13:52
  • You could add the @Assert\NotNull() annotation to cause a validation against NULL in the API, while leaving the database nullable. Commented Jan 8, 2020 at 13:56
  • As I said is not acceptable as a solution. The not null at the database level is a mandatory requirement Commented Jan 8, 2020 at 14:08
  • Oh so you don't want it nullable. Sadly API-Platform does a poor job here and requires that nullable value set in order to even execute the validation from asserting constraints. Commented Jan 8, 2020 at 14:18

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

I would set it to true, though. i.e. "disable_type_enforcement"=true . This is a workaround to a known issue: github.com/api-platform/api-platform/issues/788

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.