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?
Drupal Answers is a question and answer site for Drupal developers and administrators. It only takes a minute to sign up.
Sign up to join this communityI 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:
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');
}
}
}
public static function baseFieldDefinitions(EntityTypeInterface $entityType) {
$fields['FIELD_NAME'] = BaseFieldDefinition::create('string')
->setLabel(t('MY UNIQUE FIELD'))
->addConstraint('UniqueField');
return $fields;
}
If you want to create your own validation constraint you can check here.
A core Drupal way to achieve your result:
You will know if the ID exists if the term can be referenced. Plus this data becomes easily reusable.