Magento 2 Experten — Hyvä Theme, Tailwind CSS & SEO aus einer Hand ›

Die ersten Validierungs-Constraints

Die ersten Validierungs-Constraints

~14 Min. Lesezeit Zuletzt aktualisiert am 8. August 2026

Kapitel 16 zeigte: die API akzeptiert AKTUELL jedes syntaktisch gültige JSON – ein Project mit LEEREM Namen wird PROBLEMLOS gespeichert. Das ändert sich JETZT mit den GENAU gleichen Symfony-Validator-Constraints aus der Symfony-Schulung (Kapitel 22).

#[NotBlank] und #[Length] hinzufügen

api/src/Entity/Project.php
<?php

declare(strict_types=1);

namespace App\Entity;

use ApiPlatform\Metadata\ApiResource;
use App\Repository\ProjectRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

#[ApiResource]
#[ORM\Entity(repositoryClass: ProjectRepository::class)]
class Project
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column]
    private ?int $id = null;

    #[ORM\Column(length: 255)]
    #[Assert\NotBlank]
    #[Assert\Length(min: 3, max: 255)]
    private string $name = '';

    #[ORM\Column(type: 'text', nullable: true)]
    private ?string $description = null;

    #[ORM\Column]
    private \DateTimeImmutable $createdAt;

    // ... Getter/Setter unverändert
}

GENAU dieselben Attribute wie bei einer normalen Symfony-Formular-Validierung – use Symfony\Component\Validator\Constraints as Assert; ist der ÜBLICHE Import-Alias, um Assert\NotBlank statt des VOLLEN Klassennamens zu schreiben.

Die Validierung testen

curl -k -i -X POST https://localhost/api/projects \
  -H 'Content-Type: application/json' \
  -d '{"name": ""}'
HTTP/2 422

{
  "@context": "/api/contexts/ConstraintViolationList",
  "@type": "ConstraintViolationList",
  "hydra:title": "An error occurred",
  "hydra:description": "name: This value should not be blank.\nname: This value is too short. It should have 3 characters or more.",
  "violations": [
    {"propertyPath": "name", "message": "This value should not be blank."},
    {"propertyPath": "name", "message": "This value is too short. It should have 3 characters or more."}
  ]
}

Status 422 Unprocessable Entity statt 201 Created – GENAU der Statuscode, der bereits in der Übersichtstabelle aus Kapitel 16 angekündigt wurde. BEIDE Constraints schlagen GLEICHZEITIG fehl und erscheinen BEIDE im violations-Array.

Gültige Daten senden

curl -k -i -X POST https://localhost/api/projects \
  -H 'Content-Type: application/json' \
  -d '{"name": "Website-Relaunch"}'

Antwortet WIEDER mit 201 Created – die Validierung wird AUTOMATISCH VOR dem Speichern ausgeführt, OHNE dass wir $validator->validate() irgendwo SELBST aufrufen mussten.

Tipp: Validierung läuft bei POST, PUT UND PATCH GLEICHERMASSEN – bei PATCH werden dabei ALLE Felder geprüft (auch die NICHT im Request-Body enthaltenen), nicht nur die tatsächlich geänderten.