You are here

function relation_add_views_autocomplet in Relation add 7

Views backend relation autocomplet callback.

Return value

array|bool Return autocomplet suggestions.

1 call to relation_add_views_autocomplet()
relation_add_autocomplete in ./relation_add.module
Autocomplete page for listing entities appropriate for a given relation type.

File

modules/relation_add_views/relation_add_views.module, line 61
Relation Add View module file.

Code

function relation_add_views_autocomplet($field, $instance, $type, $direction, $target_bundles, $string) {
  $suggestions = array();
  list($view_name, $display) = explode(':', $instance['widget']['settings']['views']);
  $view = views_get_view($view_name);
  if (!$view || !isset($view->display[$display]) || !$view
    ->access($display)) {
    watchdog('relation_add_views', 'The view %view_name is no longer eligible for the %field_name field.', array(
      '%view_name' => $view_name,
      '%field_name' => $instance['label'],
    ), WATCHDOG_WARNING);
    return FALSE;
  }
  $view
    ->set_display($display);

  // Make sure the query is not cached.
  $view->is_cacheable = FALSE;
  $relation_add_views_options = array(
    'match' => $string,
    'match_operator' => 'CONTAINS',
  );
  $view->display_handler
    ->set_option('relation_add_views_options', $relation_add_views_options);
  $result = $view
    ->execute_display($display);
  if ($result) {
    $entity_infos = entity_get_info();
    foreach ($entity_infos as $entity_type => $entity_info) {
      if ($entity_info['base table'] == $view->base_table) {
        $target_type = $entity_type;
      }
    }
    $entities = entity_load($target_type, array_keys($result));
    foreach ($entities as $id => $entity) {
      $label = entity_label($target_type, $entity);
      $title = $result[$id];
      $bundle = '';
      if ($instance['widget']['settings']['relation_endpoint_bundle_display']) {
        list(, , $bundle) = entity_extract_ids($target_type, $entity);
        if (!empty($bundle)) {
          $bundle = ' - (' . $bundle . ')';
        }
      }
      $suggestions[$label . $bundle . ' [' . $target_type . ':' . $id . ']'] = $title;
    }
  }
  return $suggestions;
}