Constraint violations are not triggered for Roles' on a user's account form

Created on 17 May 2019, almost 6 years ago
Updated 27 February 2025, about 1 month ago

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.

πŸ› Bug report
Status

Active

Version

11.0 πŸ”₯

Component

user.module

Created by

πŸ‡©πŸ‡ͺGermany mmbk Meißen

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024