Error message

Deprecated function: implode(): Passing glue string after array is deprecated. Swap the parameters in drupal_get_feeds() (line 394 of /home1/tylerfra/public_html/includes/common.inc).

autocomplete

Drupal Commerce Order Owner Autocomplete with E-mail Address

When creating an order as an admin in Drupal Commerce, we can specify the user that owns the order if we know their user name. This works well in most cases, but to be able to search by the user's e-mail address would be helpful too. I've had a few requests from clients for this feature. So without further ado, let's ado it!

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  $items['my_module/commerce/order-owner/autocomplete'] = array(
    'page callback' => 'my_module_commerce_order_owner_autocomplete',
    'access arguments' => array('configure order settings'),
    'type' => MENU_CALLBACK
  );
  return $items;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_commerce_order_ui_order_form_alter(&$form, &$form_state, $form_id) {
  // Attach our custom autocomplete to the order owner name input so we can
  // search by e-mail address.
  $form['user']['name']['#autocomplete_path'] = 'my_module/commerce/order-owner/autocomplete';
}

/**
 * Queries results for the commerce order owner autocomplete.
 */
function my_module_commerce_order_owner_autocomplete($string) {
  $matches = array();
  $query = db_select('users', 'u');
  $query
    ->fields('u', array('uid', 'name', 'mail'))
    ->condition(db_or()
      ->condition("u.mail", '%' . db_like($string) . '%', 'LIKE')
      ->condition("u.name", '%' . db_like($string) . '%', 'LIKE')
    )
    ->condition('u.uid', 0, '<>')
    ->range(0, 10);
  $results = $query->execute();
  foreach ($results as $row) {
    $key = "$row->name";
    $matches[$key] = "$row->name - $row->mail ($row->uid)";
  }
  drupal_json_output($matches);
}

Drupal User Entity Reference Field with Custom Autocomplete that uses an Address Field

User reference fields (aka entity reference fields) are great. As you may have guessed, we can use these fields to reference users on other entities (e.g. nodes).

Say we had a user reference field on the Article content type... by default, when selecting a user to reference, we could configure the field widget to be an autocomplete. This allows us to begin typing the user's login name as a way to reference them. This works well in most cases.

What if we had an address field on our user entities, and collected the user's first and last names? It may be more usable for site administrators to be able to search across the user's actual name instead of their user name for logging in.

We can use hook_menu(), hook_form_BASE_FORM_ID_alter(), and a custom callback function to provide a custom autocomplete widget that searches across our address field's values instead...

Subscribe to RSS - autocomplete