Symfony 8.2 New Published on

Checking that an identifier exists, with #[EntityExists]

#[EntityExists] checks that an identifier received by the API points to an entity: a clear 422 instead of a 500 error in the controller.

Topics covered: ValidatorDoctrine

New in Symfony 8.2 (in development). An API often receives identifiers: a user's ID, a product reference. The Validator could say a value is unique (#[UniqueEntity]), not that it exists. So the controller called find(), and sometimes forgot the null case: a 500 error for a mere typo from the client.

#[EntityExists]

The Doctrine bridge's new constraint checks that the value points to an entity, and reports a violation on the property otherwise:

use Symfony\Bridge\Doctrine\Validator\Constraints\EntityExists;

final class AssignOrder
{
    #[Assert\NotBlank]
    #[EntityExists(entityClass: User::class)]
    public string $userId;

    #[EntityExists(entityClass: Product::class, identifierField: 'sku')]
    public ?string $productSku = null;
}
  • entityClass: the entity to look in;
  • identifierField: look up by a field other than the identifier;
  • repositoryMethod: call a repository method with the value; a “truthy” result (an entity, a non-zero number, true) means the entity exists. The last two options can't be combined.

null and the empty string are valid: add NotBlank when the value is required.

Your task

POST /orders/assign hands an order over to a salesperson, and can add a free product to it. The request goes through #[MapRequestPayload], so through the Validator, but nothing there checks that the salesperson or the product exist: the “Assign to an unknown salesperson” request in the “Requests” tab ends in a 500 error. To fill the preview's database, open the home page first.

  1. Reject an unknown salesperson, with the message “No salesperson has this identifier.”.
  2. Reject an unknown product or one no longer on sale, with “This product is not on sale.”. The product stays optional.

Where the feature comes from: the original pull request.