Unique field constraint does not work with any field main property name that is not "value"

Created on 17 May 2018, about 6 years ago
Updated 13 September 2023, 10 months ago

Problem/Motivation

Adding a constraint of UniqueField to an entity reference field does not enforce that the field value is unique.

One was added by:

function hook_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if (!empty($fields['field_some_reference'])) {
    $fields['field_some_reference']->addConstraint('UniqueField', [
      'message' => 'An entity reference %value already exists.'
    ]);
  }
}

Proposed resolution

The problem seems to stem from UniqueFieldValueValidator.php on line 30.

$value_taken = (bool) \Drupal::entityQuery($entity_type_id)
    // The id could be NULL, so we cast it to 0 in that case.
    ->condition($id_key, (int) $items->getEntity()->id(), '<>')
    ->condition($field_name, $item->value)
    ->range(0, 1)
    ->count()
    ->execute();

$item->value returns nothing for an entity reference field even if a value is present.

Being that it's not the only field type that behaves this way, I am not sure what the best approach is that will cover all field types.

Remaining tasks

🐛 Bug report
Status

Closed: duplicate

Version

11.0 🔥

Component
Field 

Last updated about 5 hours ago

Created by

🇺🇸United States mstef

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024