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:
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'); } } }
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:
- AllowedValuesConstraint : Checks for the value being allowed.
- ComplexDataConstraint : Validates properties of complex data structures.
- CountConstraint : Count constraint.
- EmailConstraint : Count constraint.
- IsNullConstraint : Null constraint.
- LengthConstraint : Length constraint.
- NotNullConstraint : NotNull constraint.
- PrimitiveTypeConstraint : Supports validating all primitive types.
- RangeConstraint : Range constraint.
- RegexConstraint : Regex constraint.
- UniqueFieldConstraint : Checks if an entity field has a unique value.
- UuidConstraint : Validates a UUID.
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 !