You are here

function farm_asset_autocomplete in farmOS 7

Page callback for the farm_asset autocomplete path.

Parameters

string $asset_type: The asset type to filter to. If this is set to 'all' then no filtering will be performed. Multiple asset types can be specified as a single string, separated by plus characters (+). ie: "animal+group"

string $string: The text field asset name(s) to search for.

Return value

array Returns an array of matching assets in JSON form.

1 string reference to 'farm_asset_autocomplete'
farm_asset_menu in modules/farm/farm_asset/farm_asset.module
Implements hook_menu().

File

modules/farm/farm_asset/farm_asset.module, line 724
Farm asset - A farm asset entity type.

Code

function farm_asset_autocomplete($asset_type, $string) {

  // The user enters a comma-separated list of tags. We only autocomplete the last tag.
  $tags_typed = drupal_explode_tags($string);
  $tag_last = drupal_strtolower(array_pop($tags_typed));

  // Search the database for assets with matching names
  $query = db_select('farm_asset', 'fa')
    ->fields('fa', array(
    'id',
    'name',
    'archived',
  ))
    ->condition('name', '%' . db_like($tag_last) . '%', 'LIKE')
    ->orderBy('name', 'ASC')
    ->range(0, 10);

  // If the asset type is not "all", filter by asset type.
  if ($asset_type != 'all') {
    $asset_types = array();
    if (strpos($asset_type, '+') !== FALSE) {
      $asset_types = explode('+', $asset_type);
    }
    else {
      $asset_types[] = $asset_type;
    }
    $query
      ->condition('type', $asset_types, 'IN');
  }

  // Execute the query.
  $result = $query
    ->execute();

  // Save matches to an array, including the asset name and ID.
  $matches = array();
  foreach ($result as $row) {

    // Generate a prefix of previously matched tags.
    $prefix = count($tags_typed) ? drupal_implode_tags($tags_typed) . ', ' : '';

    // We use htmlspecialchars() instead of check_plain() to preserve single
    // quotes (apostrophes) in asset names.
    $match = htmlspecialchars($row->name) . ' [id: ' . $row->id . ']';
    if (!empty($row->archived)) {
      $match .= ' (' . t('archived') . ')';
    }

    // Add match to list of matches.
    $matches[$prefix . $match] = $match;
  }

  // Return the matches as JSON.
  drupal_json_output($matches);
}