3

I am writing my own module. I want to display a taxonomy terms as a autocomplete field in my form using form API. How can I do that?

I am using Drupal7.

8

Hope this will help you,

In Drupal 7, it can be done in 2 ways

  • By using existing taxonomy field(like TAG field), for this example I'm using field_tag
    $node=node_load($nid);
    $tags = array();
    foreach ($node->field_tags['und'] as $item) {
      $tags[$item['tid']] = isset($item['taxonomy_term']) ? $item['taxonomy_term'] : taxonomy_term_load($item['tid']);
    }
    $form['tags'] = array(
      '#type' => 'textfield',
      '#default_value' => taxonomy_implode_tags($tags),
      '#title' => 'Add Tags',
      '#autocomplete_path' => 'taxonomy/autocomplete/field_tags',
      '#maxlength' => 1024,
      '#element_validate' => array('taxonomy_autocomplete_validate'),page
    );
    
  • If you dont want to use any field then it can also be using custom autocomplete
    //custom field
    $form['taxonomy_term_field'] = array(
      '#type' => 'textfield',
      '#autocomplete_path' => 'get_TAXONOMY_NAME/autocomplete',
    );
    //menu callback for autocomplete
    function HOOK_menu() {
      $items = array();
      ....
      $items['get_TAXONOMY_NAME/autocomplete/%'] = array(
        'page callback' => 'TAXONOMY_NAME_autocomplete_callback',
        'page arguments' => array(2),
        'type' => MENU_CALLBACK,
      ); 
      return $items;
    }
    //autocomplete callback function
    function TAXONOMY_NAME_autocomplete_callback($str = 0) {
      $matches = array();
      //vocabulary id
      $vid = 2;
      $result = db_select('taxonomy_term_data', 't')
        -> fields('t', array('tid', 'name'))
        -> condition('vid', $vid, '=')
        -> condition('name', $str.'%%', 'LIKE')
        -> range(0, 10)
        -> execute();
      foreach ($result as $term) {
        $matches[$term -> tid] = check_plain($term -> name);
      }
      drupal_json_output($matches);
    }
    
    References : Existing taxonomy field and Custom autocomplete field
2
$form['nameField'] = array(
    '#type' => 'textfield',
    '#autocomplete_path'=>'example/autocomplete'
);

//HOOK_MENU
 function MODULENAME_menu() {
    $items['example/autocomplete'] = array(
    'title' => '',
    'description' => '',
    'page callback' => 'example_autocomplete',
    'access callback' => TRUE,
);

 function example_autocomplete() {
    $termes = taxonomy_vocabulary_get_names();
    $vocabulary = taxonomy_get_tree($termes['MACHINENAME']->vid);
    $list = array();
    foreach ($vocabulary as $taxonomy){
           $list[$taxonomy->tid] = $taxonomy->name;
    }
    print drupal_json_encode($list);
    exit();
}
  • It is not working in my end. – Fawwad Apr 26 '16 at 5:54
1

1) Custom Module name : common_operations

2)


/**
 *Implements hook_menu()
 */
function common_operations_menu() {
  $items['autocomplete/taxonomy'] = array(
    'title' => 'Menu Title',
    'description' => 'Menu description',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('common_operations_autocomplete_taxonomy_form'),
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  $items['path/autocomplete'] = array(
    'title' => 'Custom Autocomplete',
    'page callback' => 'common_operations_custom_autocomplete',
    'access arguments' => array('access taxonomy autocomplete'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

/**
  *Defines autocomplete_taxonomy_form()
  *@param $form
  *@param &$form_state 
  *@return $form
  */
function common_operations_autocomplete_taxonomy_form($form, &$form_state) {
  $form['taxonomy'] = array(
    '#type' => 'textfield',
    '#title' => t('Campus'),
    '#autocomplete_path' => 'path/autocomplete',
    '#maxlength' => 60,
    '#size' => 15,
    '#required' => 0,
  );

  //--------------------Others------------------

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Lets Go!'),
  );

  return $form;
}

/**
 *Page callback for menu 'path/autocomplete'
 */
function common_operations_custom_autocomplete($string) {
  $matches = array();
  $result = db_select('taxonomy_term_data', 'ttd');
  $result->fields('ttd', array('tid', 'name'));
  $result->condition('vid', array(VID1, VID2,...), 'IN');
  $result->condition(db_or()->condition('ttd.name', '%' . db_like($string) . '%', 'LIKE'));
  $query = $result->execute();

  foreach ($query as $row) {     
    $matches[$row->tid] = $row->name; 
  }

  // Return the result to the form in json
  drupal_json_output($matches);
}

/**
 * Implements hook_permission().
 */
function common_operations_permission() {
  return array(
    'access taxonomy autocomplete' => array(
      'title' => t('Access Custom Taxonomy Autocomplete'),
        'description' => t('Access permission of Custom Taxonomy Autocomplete.'),
    ),
  );
}

3) Replace VID1, VID2, ... with the Vocabulary ID's

4) Clear drupal cache

5) Set Permission

6) Access path 'autocomplete/taxonomy' & try

Hope it helps

Not the answer you're looking for? Browse other questions tagged or ask your own question.