Skip to main content

Create unique field in a content type

If you want to add a unique field to content type so that Drupal would prevent you from entering the same field value more than once 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'])) {
          $fields['FIELD_NAME']->addConstraint('UniqueField');
        }
      }
    }

     
  2. 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'))
       ->addConstraint('UniqueField');
    
     return $fields;
    }