I'm currently working on performing some custom validation to an entity using constraints (also custom ones) and the validator component. I want to get the specified constraints to an Entity by group to apply the correct constraints group.
I saw this old question for Symfony 2 and seems it doesn't work in Symfony 4.
The entity User.php:
class User
{
private $id;
private $email;
private $origin;
...
}
The configured constraints in a validation.yaml file:
App\Domain\User:
properties:
origin:
- NotBlank: { groups: [user_create] }
- NotNull: { groups: [user_update] }
The validation process:
// Get the component by injection and gets valid metadata
// Also gets the validation groups user_* for origin field
$metadata = $this->validator->getMetadataFor(User::class);
// This returns an empty array
$constraints = $metadata->findConstraints('user_create');
// This also returns an empty array
$constraints = $metadata->findConstraints('Default');
// Empty violations because constraints are empty
$violations = $this->validator->validate($leadRequest, $constraints, 'user_create');
Dump of $metadata:
ClassMetadata^ {#1551
+name: "App\Domain\User"
+defaultGroup: "User"
+members: array:11 [
"origin" => array:1 [
0 => PropertyMetadata^ {#2472
+class: "App\Domain\User"
+name: "origin"
+property: "origin"
-reflMember: array:1 [
"App\Domain\User" => ReflectionProperty {#2223
+name: "origin"
+class: "App\Domain\User"
modifiers: "private"
}
]
+constraints: array:4 [
0 => NotBlank^ {#5590
+message: "This value should not be blank."
+allowNull: false
+normalizer: null
+payload: null
+"groups": array:1 [
0 => "user_create"
]
}
1 => NotNull^ {#5567
+message: "This value should not be null."
+payload: null
+"groups": array:1 [
0 => "user_update"
]
}
...
There is not any documentation about this feature so maybe this method is no longer valid or I'm doing something wrong.
Thank you for your help.
$this->validator->validate($leadRequest, null, 'user_create');? I mean, if you need to perform a validation against a particular "group", just use it. The$constraintsfield could be useful only if you need a "sub-set" of constraint under the same "group"config/validator/validation.yamlas said in the validator docs.User.phpin the right namespace? And did you enable the validation as shown in symfony.com/doc/current/validation.html#configuration