You are here

function unique_field_ajax_is_unique in Unique field ajax 8

Same name and namespace in other branches
  1. 2.x unique_field_ajax.module \unique_field_ajax_is_unique()

Test if the field value already exist in the database.

Parameters

$entity_type:

$langcode:

$field_name:

$field_value:

$bundle:

$is_unique_per_lang:

Return value

array|int

2 calls to unique_field_ajax_is_unique()
unique_field_ajax_validate_unique in ./unique_field_ajax.module
Ajax callback to validate the email field.
_unique_field_ajax_process in ./unique_field_ajax.module
Attach ajax to unique field.

File

./unique_field_ajax.module, line 238
Unique value for cck fields check module.

Code

function unique_field_ajax_is_unique($entity_type, $langcode, $field_name, $field_value, $bundle, $is_unique_per_lang, $entity) {
  $entity_type_definition = Drupal::entityTypeManager()
    ->getDefinition($entity_type);
  $query = Drupal::entityQuery($entity_type)
    ->condition($field_name, $field_value, '=');

  // Test if the entity has a bundle.
  if (!empty($entity_type_definition
    ->getKey('bundle'))) {
    $query
      ->condition($entity_type_definition
      ->getKey('bundle'), $bundle, '=');
  }

  // Test unique per language.
  if ($is_unique_per_lang) {
    $query
      ->condition('langcode', $langcode);
  }
  $entities = $query
    ->execute();
  if (!empty($entities)) {
    if ($id = $entity
      ->id()) {
      if (!in_array($id, $entities)) {
        return FALSE;
      }
    }
    else {
      return FALSE;
    }
  }
  return TRUE;
}