You are here

function entityreference_field_validate in Entity reference 8

Same name and namespace in other branches
  1. 7 entityreference.module \entityreference_field_validate()

Implements hook_field_validate().

File

./entityreference.module, line 137
Provides a field that can reference other entities.

Code

function entityreference_field_validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {
  $ids = array();
  foreach ($items as $delta => $item) {
    if (!entityreference_field_is_empty($item, $field) && $item['target_id'] !== NULL) {
      $ids[$item['target_id']] = $delta;
    }
  }
  if ($ids) {
    $valid_ids = entityreference_get_selection_handler($field, $instance, $entity_type, $entity)
      ->validateReferencableEntities(array_keys($ids));
    $invalid_entities = array_diff_key($ids, array_flip($valid_ids));
    if ($invalid_entities) {
      foreach ($invalid_entities as $id => $delta) {
        $errors[$field['field_name']][$langcode][$delta][] = array(
          'error' => 'entityreference_invalid_entity',
          'message' => t('The referenced entity (@type: @id) is invalid.', array(
            '@type' => $field['settings']['target_type'],
            '@id' => $id,
          )),
        );
      }
    }
  }
}