Problem/Motivation
Im trying to deny certain combination of user roles while creating or editing a user.
For this purpose I created a Constraint that should check whether the entered combination of roles is allowed. After implementing this, I experienced that the ConstraintValidator is executed, but the violation is not honoured by the underlying routines.
To verify that my Contraint implemantation is correct, I added the same Constraint to the name and mail field in the same form. On this fields the Constraint works as expected. Im not sure whether I missed something, but my implementation seems to be correct as it's working on the other fields.
---- htdocs/modules/my_module/src/Plugin/Validation/Constraint/UserRolesConstraint.php ----
<?php
namespace Drupal\my_module\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
/**
* Class UserRolesConstraint
*
* @Constraint(
* id = "UserRoles",
* label = @Translation("User roles restrictions",context = "Validation")
* )
*
*/
class UserRolesConstraint extends Constraint{
public $ClientMustHaveOnlyOneGroup = 'Invalid roles selection.';
}
---- htdocs/modules/my_module/src/Plugin/Validation/Constraint/UserRolesConstraintValidator.php ----
<?php
namespace Drupal\my_module\Plugin\Validation\Constraint;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
/**
* Class UserGroupConstraintValidator
*
* @package Drupal\my_module\Plugin\Validation\Constraint
*/
class UserRolesConstraintValidator extends ConstraintValidator {
/**
* @inheritdoc
*/
public function validate($value, Constraint $constraint) {
$this->context->addViolation( $constraint->ClientMustHaveOnlyOneGroup);
}
}
---- htdocs/modules/my_module/my_module.module ----
/**
* Implements hook_entity_base_field_info_alter().
*/
function my_module_entity_base_field_info_alter(&$fields, EntityTypeInterface $entityType) {
if ($entityType->id() == 'user') {
$fields['roles']->addConstraint('UserRoles');
$fields['name']->addConstraint('UserRoles');
$fields['mail']->addConstraint('UserRoles');
}
}
Attached is a screen shot of the result, I would have expected the the 'Roles' were marked as error as well.