UniqueFieldValueValidator works only with single value fields

Created on 27 April 2015, over 9 years ago
Updated 26 June 2024, 6 months ago

The \Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator works with only single value field and therefore it cannot be used with fields that have multiple values, like string lists.

On line #34 the condition is:

$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, db_like($items->first()->value), 'LIKE')
      ->range(0, 1)
      ->count()
      ->execute();

instead it should be:

$values = array();
foreach ($items->getIterator() AS $item) {
  // The original code uses $item->value and although I prefer $item->getValue()
  // we don't know what the key for the field will be so using 'value' is ok.
  $values[] = $item->value;
}

$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, $values, 'IN')
     // Or ->condition($field_name, ':values[]', 'IN', array(':values[]' => $values))
     // I'm not sure what the current approach is.
      ->range(0, 1)
      ->count()
      ->execute();

Steps to reproduce

Add the UniqueField constraint to a field by putting the following hook into a custom .module file:

/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function MYMODULE_entity_bundle_field_info_alter(&$fields, \Drupal\Core\Entity\EntityTypeInterface $entity_type, $bundle) {
  if ($bundle === 'YOUR_BUNDLE' && !empty($fields['field_YOUR_FIELD'])) {
    $fields['field_YOUR_FIELD']->addConstraint('UniqueField', []);
  }
}

If your field is multi-valued the validation will not work past the first delta. For example, if you have a multi-value plaintext field and you repeatedly input "aaa" then the constraint will allow it. This is also the case across different entities; it will check the first delta on each entity but not beyond it.

Additionally, per issue 2973455 the validator also will not validate entity reference fields or compound fields such as links.

šŸ“Œ Task
Status

Fixed

Version

11.0 šŸ”„

Component
FieldĀ  ā†’

Last updated about 22 hours ago

Created by

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.71.5 2024