function unique_field_ajax_is_unique in Unique field ajax 2.x
Same name and namespace in other branches
- 8 unique_field_ajax.module \unique_field_ajax_is_unique()
Test if the field value already exist in the database.
Parameters
string $entity_type: Entity type name.
string $lang_code: Language code.
string $field_name: Field name.
string $field_value: Field value.
string $bundle: Bundle.
bool|null $is_unique_per_lang: Is unique per lang flag.
\Drupal\Core\Entity\EntityBase $entity: The entity object.
Return value
bool|string Boolean TRUE if the value is unique. In any other case, the entity ID of the entity that has the same value.
Throws
\Drupal\Component\Plugin\Exception\PluginNotFoundException
2 calls to unique_field_ajax_is_unique()
- unique_field_ajax_validate_unique in ./
unique_field_ajax.module - Element Validate callback to validate a field.
- _unique_field_ajax_process in ./
unique_field_ajax.module - Attach ajax to unique field.
File
- ./
unique_field_ajax.module, line 528 - Unique value for cck fields check module.
Code
function unique_field_ajax_is_unique(string $entity_type, string $lang_code, string $field_name, string $field_value, string $bundle, ?bool $is_unique_per_lang, EntityBase $entity) {
$entity_type_definition = Drupal::entityTypeManager()
->getDefinition($entity_type);
$query = Drupal::entityQuery($entity_type)
->range(0, 1)
->condition($field_name, $field_value, '=');
if (!$entity
->isNew()) {
$query
->condition($entity_type_definition
->getKey('id'), $entity
->id(), '<>');
}
// 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', $lang_code);
}
$entities = $query
->execute();
if (!empty($entities)) {
return array_shift($entities);
}
return TRUE;
}