How do I override the $message value of the UniqueFieldConstraint class? 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(&amp;$fields, EntityTypeInterface $entity_type, $bundle) {

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

        $fields['field_custome_no']-&gt;addConstraint('UniqueField', []);
        //The below code not setting Custom Error Message       
        UniqueFieldConstraint::$message = "Custom Error Message";   
      }
    }
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.


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.';
}

Implement hook_validation_constraint_alter() to swap out the existing constraint for yours:

function [MODULE]_validation_constraint_alter(array &amp;$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).