I read this article: "Textfield that uses autocomplete" and I am implemented a form with autocomplete successfully.
Now, I need a radio select, with two options: "user" or "title" that when clicked, should return to autocomplete the user's name or node's title as the selected option.
How can I do this?
If I set an attribute "onchange" in the "field_radio", how do I know the option chosen in function "_set_autocomplete" ?
Any tips ?

The form:

function myfunction_form($form, &$form_state) {
  $form['field_text'] = array(
      '#type' => 'textfield',
      '#autocomplete_path' => 'pathto/autocomplete',
  $form['field_radio'] = array(
      '#type' => 'radios',
      '#options' => array(
        '1' => t('Title'),
        '2' => t('Name')),
      '#default_value' => '1',
  $form['submit'] = array(
      '#type' => 'image_button',
      '#src' => 'bt-image.gif',
  return $form;

The path

function mymodule_menu() {
  $items['pathto/autocomplete'] = array(
      'page callback' => '_set_autocomplete',
      'access callback' => TRUE,
      'type' => MENU_CALLBACK
  return $items;

The logic

function _set_autocomplete($string) {
  $matches = array();

  //Select table
  $query = db_select('node', 'n');

  $return = $query
      ->fields('n', array('title'))
      ->condition('n.status', 1)
      ->condition('n.type', 'page')
      ->condition('n.title', '%' . db_like($string) . '%', 'LIKE')
      ->range(0, 20)

  //Add matches in $matches.
  foreach ($return as $row) {
    $matches[$row->title] = check_plain($row->title);
  //Return for JS



nevets’s picture

One approach would be to use two text fields and use states to hide/show the appropriate one. The developers examples module includes an example using states.

And alternative approach would be to ajaxify the form so you set the auto complete path based on the current choice of the radio button. The examples module includes example of using ajax in forms but nothing that is exactly what you would need

Side note, there are auto complete paths for both nodes and users.

coyoterj’s picture

Hi nevets,

The first suggestion with two textfields worked perfectly.

Thank you! Thank you! :)