Sunday, August 14, 2011

Auto Complete form field with multiple Values


To create an auto-complete field in Drupal, all you need to do to is to use the From API attribute #autocomplete_path and associate with a custom menu callback that provides the AJAX response for the auto-complete field. The custom menu callback can define the query that needs to be made in the database before a result is returned. The below code can b used to create a multi-select auto-complete field.

The best examples of the auto-complete field in core are the author field in node create and edit and taxonomy auto-complete.

function my_module_menu() {

$items['my-module/my-autocomplete'] = array(
    'title' =>'My module autocomplete',
    'page callback' => 'my_module_autocomplete',
    'access callback' => 'my_access',
    'access arguments' => array('my module access'),
    'type' => MENU_CALLBACK,
  );
 return $items;
}


function my_module_autocomplete($string = '') {
  $array = drupal_explode_tags($string);

  // Fetch last value
  $last_string = trim(array_pop($array));
  $matches = array();
  if ($last_string){
    $result =  Define Query here... 
    while($obj = db_fetch_object($result)) {
      $prefix = count($array) ? implode(', ', $array) .', ' : '';
      $matches[$prefix.$obj->;name] = check_plain($obj->name);
    }
  }
 drupal_json($matches);
}


Reference:
1. Helper function taxonomy_autocomplete in taxonomy module
2. Function user_autocomplete in user module.

1 comment:

  1. this post is very nice..collections are great..i likes it…keep posting more blogs..i wish u for a great future..

    ReplyDelete

Search This Blog

Chennai Drupal Community

drupal.org - Community plumbing

Shyamala's Drupal SEO