You are here

function commerce_product_autocomplete in Commerce Core 7

Returns output for product autocompletes.

The values returned will be keyed by SKU and appear as such in the textfield, even though the preview in the autocomplete list shows "SKU: Title".

1 string reference to 'commerce_product_autocomplete'
commerce_product_menu in modules/product/commerce_product.module
Implements hook_menu().

File

modules/product/commerce_product.module, line 740
Defines the core Commerce product entity, including the entity itself, the bundle definitions (product types), and various API functions to manage products and interact with them through forms and autocompletes.

Code

function commerce_product_autocomplete($entity_type = 'commerce_product', $field_name = NULL, $bundle = NULL, $string = '') {
  $matches = array();

  // Extract the SKU string from the URL while preserving support for SKUs that
  // contain slashes. Whereas we previously relied on the $string parameter, its
  // value was being truncated when any SKUs in the autocomplete widget had a /.
  // @see http://drupal.org/node/1962144
  $args = explode('/', request_path());
  if (count($args) <= 5) {
    drupal_json_output($matches);
    return;
  }

  // Trim off leading arguments from other modules such as Locale.
  $offset = array_search('commerce_product', $args);
  array_splice($args, 0, 5 + $offset);
  $string = implode('/', $args);

  // 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));
  if (!empty($tag_last)) {
    $prefix = count($tags_typed) ? implode(', ', $tags_typed) . ', ' : '';
    $field = field_info_field($field_name);
    $instance = field_info_instance($entity_type, $field_name, $bundle);

    // Determine the type of autocomplete match to use when searching for products.
    $match = isset($field['widget']['autocomplete_match']) ? $field['widget']['autocomplete_match'] : 'contains';

    // Get an array of matching products.
    $products = commerce_product_match_products($field, $instance, $tag_last, $match, array(), 10, TRUE);

    // Loop through the products and convert them into autocomplete output.
    foreach ($products as $product_id => $data) {
      $matches[$prefix . $data['sku']] = $data['rendered'];
    }
  }
  drupal_json_output($matches);
}