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?


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.


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, privacy policy and cookie policy

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