Drupal 8 How to add constraint to filed in a content type as (Unique, Count ... ) !

Profile picture for user a.berramou
Azz-eddine BERRAMOU 18 March, 2020

Sometimes you need to make some fields unique, for instance you need to create all articles with unique title.

For Drupal 7 there is a module Unique field but it's not ported to Drupal 8 yet,  to do so there is two options:

  1. If your field created using UI or it's already created by Drupal like (Title, Body ...)
    you should implement hook_entity_bundle_field_info_alter and add another constraint using addConstraint like the following:

    <?php
    
    use Drupal\Core\Entity\EntityTypeInterface;
    /**
     * Implements 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. If you are creating a custom field programmatically you can addConstraint in your baseFieldDefinitions method like the following:

    <?php
    
    public static function baseFieldDefinitions(EntityTypeInterface $entityType) {
     $fields['FIELD_NAME'] = BaseFieldDefinition::create('string')
       ->setLabel(t('MY UNIQUE FIELD'))
       ->addConstraint('UniqueField');
    
     return $fields;
    }

 

Heres is the complete list of accepted constraints you can pass to addConstraint:

Note : All above constraints code located in core/lib/Drupal/Core/Validation/Plugin/Validation/Constraint folder.

You can do even more better, you can Create custom constraint !