I have an Employee content type with an ID field.

Can I make the field unique, so that Drupal would prevent me from entering the same ID more than once by mistake?


2 Answers 2


You can add a validation constraint to your field.
There is two ways to do that:

  1. Setting a validation constraint to a field you haven't defined by implementing hook_entity_bundle_field_info_alter:
function YOURMODULE_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if ($entity_type->id() === 'ENTITY_TYPE' && $bundle === 'BUNDLE_NAME') {
    if (isset($fields['FIELD_NAME'])) {
  1. Setting a validation constraint to a field you have defined in baseFieldDefinitions
public static function baseFieldDefinitions(EntityTypeInterface $entityType) {
 $fields['FIELD_NAME'] = BaseFieldDefinition::create('string')
   ->setLabel(t('MY UNIQUE FIELD'))

 return $fields;

If you want to create your own validation constraint you can check here.

  • It is maybe worth noting that UniqueField will check uniqueness across all nodes (or whatever entity type you are using). So eg if you have a Rank field in two content types, there can be only one Rank #1. Feb 28 at 1:43

A core Drupal way to achieve your result:

  1. Create Taxonomy "Employee ID".
  2. Add Taxonomy reference field to "Employee" content type.
  3. Ensure to check "Create referenced entities if they don't already exist" in field settings.

You will know if the ID exists if the term can be referenced. Plus this data becomes easily reusable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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