2

I am new to Drupal 8 and I have added Core Constraint called "UniqueField" on my custom field "Customer_no" which is attached user to Entity. Below is that code which I am trying to override error Message but its not working:

  function devel_reg_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {

      if ($entity_type->id() == 'user' && isset($fields['field_customer_number_reseller_i'])) {

        $fields['field_custome_no']->addConstraint('UniqueField', []);
        //The below code not setting Custom Error Message       
        UniqueFieldConstraint::$message = "Custom Error Message";   
      }
    }
2

The message is hard-coded into UniqueFieldConstraint. It's a public property, so there may be a way to set it that I don't know about. However, another way to go about it is to extend UniqueFieldConstraint, set your own message, and tell the system to use your class instead of the original.

  1. Extend the class:

    namespace Drupal\[MODULE]\Plugin\Validation\Constraint;
    
    use Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldConstraint;
    
    class [MODULE]UniqueFieldConstraint extends UniqueFieldConstraint {
      public $message = 'Something about an @entity_type with a @field_name and value of %value.';
    }
    
  2. Implement hook_validation_constraint_alter() to swap out the existing constraint for yours:

    function [MODULE]_validation_constraint_alter(array &$definitions) {
      $definitions['UniqueField']['class'] = '\\Drupal\\[MODULE]\\Validator\\Constraints\\[MODULE]UniqueFieldConstraint';
    }
    

Note that [MODULE] should be swapped out with the appropriate value, and the class should be placed in the appropriate folder for the given namespace.

Update: Or, as 4k4 mentioned, you can add @Constraint annotation to the constraint above, creating a new constraint. This new constraint can then be explicitly attached to whatever it is that needs constraining.

Which method to use will depend on whether you want to override the UniqueFieldConstraint message any time it is called (the original method I outlined) or whether you want to explicitly attach the constraint to specific items (4k4's method).

  • 2
    Alternatively to step 2 you can add a custom constraint ID to the class annotations @Constraint(id="MyUniqueConstraint"), which would be discovered automatically, and you can use it without overriding the core constraint. – 4k4 Dec 16 '19 at 14:07
  • Updated accordingly. – Jaypan Dec 16 '19 at 14:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.