Skip to content

Commit 0a088a5

Browse files
authored
feat(doc): add description of how to validate item delete operations (#1527)
1 parent 9b49010 commit 0a088a5

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

core/validation.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,89 @@ class Greeting
377377
}
378378
```
379379

380+
## Validating Delete Operations
381+
382+
By default, validation rules that are specified on the API resource are not evaluated during DELETE operations. You need to trigger the validation in your code, if needed.
383+
384+
Assume that you have the following entity that uses a custom delete validator:
385+
386+
```php
387+
<?php
388+
// api/src/Entity/MyEntity.php
389+
390+
namespace App\Entity;
391+
392+
use ApiPlatform\Core\Annotation\ApiResource;
393+
use App\Validator\AssertCanDelete;
394+
use Doctrine\ORM\Mapping as ORM;
395+
396+
#[ORM\Entity]
397+
#[ApiResource(
398+
itemOperations: [
399+
'delete' => [
400+
'validation_groups' => ['deleteValidation']
401+
]
402+
]
403+
)]
404+
#[AssertCanDelete(groups: ['deleteValidation'])]
405+
class MyEntity
406+
{
407+
#[ORM\Id, ORM\Column, ORM\GeneratedValue]
408+
private ?int $id = null;
409+
410+
#[ORM\Column]
411+
public string $name = '';
412+
}
413+
```
414+
415+
Create a data persister, which decorates the default data persister, where you will trigger the validation:
416+
417+
```php
418+
<?php
419+
// api/src/DataPersister/MyEntityDataPersister.php
420+
421+
namespace App\DataPersister;
422+
423+
use ApiPlatform\Core\DataPersister\DataPersisterInterface;
424+
use ApiPlatform\Core\Validator\ValidatorInterface;
425+
use App\Entity\MyEntity;
426+
427+
class MyEntityDataPersister implements DataPersisterInterface
428+
{
429+
public function __construct(
430+
private DataPersisterInterface $decoratedDoctrineDataPersister,
431+
private ValidatorInterface $validator,
432+
) {
433+
}
434+
435+
public function persist($data): void {
436+
$this->decoratedDoctrineDataPersister->persist($data);
437+
}
438+
439+
public function remove($data): void {
440+
$this->validator->validate(
441+
$data,
442+
['groups' => ['deleteValidation']]
443+
);
444+
$this->decoratedDoctrineDataPersister->remove($data);
445+
}
446+
447+
public function supports($data): bool {
448+
return $data instanceof MyEntity;
449+
}
450+
}
451+
```
452+
453+
Register the new data persister in `api/config/services.yaml`:
454+
455+
```yaml
456+
# api/config/services.yaml
457+
services:
458+
_defaults:
459+
bind:
460+
$decoratedDoctrineDataPersister: '@api_platform.doctrine.orm.data_persister'
461+
```
462+
380463
## Error Levels and Payload Serialization
381464
382465
As stated in the [Symfony documentation](https://symfony.com/doc/current/validation/severity.html), you can use the payload field to define error levels.

0 commit comments

Comments
 (0)