You are here

function entity_autocomplete_element_validate in Entity Autocomplete 7

Validate an entity autocomplete element.

1 string reference to 'entity_autocomplete_element_validate'
entity_autocomplete_element_info in ./entity_autocomplete.module
Implements hook_element_info().

File

./entity_autocomplete.module, line 222
Provides functionalities for entity fields autocompletion.

Code

function entity_autocomplete_element_validate($element, &$form_state, $form) {
  if (!empty($element['#value'])) {
    $info = entity_get_info($element['#entity_type']);
    $table = $info['base table'];
    $id_field = $info['entity keys']['id'];
    $query = db_select($table);
    $query
      ->addField($table, $id_field);
    $query
      ->condition($id_field, entity_autocomplete_get_id($element['#value']));
    if ($element['#bundles']) {
      $bundle_field = $info['entity keys']['bundle'];
      $bundles = (array) $element['#bundles'];

      // Handle taxonomy seperately as its bundles work differently.
      if ($element['#entity_type'] === 'taxonomy_term') {
        $vids = array();
        foreach (taxonomy_get_vocabularies() as $vid => $vocab) {
          $vids[$vocab->machine_name] = $vid;
        }
        $bundles = array_intersect_key($vids, array_flip($bundles));
        $bundle_field = 'vid';
      }
      $query
        ->condition($bundle_field, $bundles);
    }
    if (!$query
      ->execute()
      ->fetch()) {
      form_error($element, t('The specified entity %value does not match requirements.', array(
        '%value' => $element['#value'],
      )));
    }
  }
}