How to make autocomplete return nid and name? My question is about textfield autocomplete. I have this code:

function my_module_menu(){
  $items['my_module/textfield_autocomplete'] = array(
    'page callback' =&gt; 'my_module_textfield_autocomplete',
    'file' =&gt; '.\my_module\my_module.inc',
    'type' =&gt; MENU_CALLBACK,
    'access arguments' =&gt; array('access example autocomplete'),
  );
  return $items;
}


In my_module.module:

$form['fieldset7-wrapper']['prop'][$i] = array(
          '#type' =&gt; 'textfield',
          '#title' =&gt; t('Nombre de propietario'),
          // The autocomplete path is provided in hook_menu in ajax_example.module.
          '#autocomplete_path' =&gt; 'my_module/textfield_autocomplete'
        );


In my_module.inc:

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

  // Some fantasy DB table which holds clientes

  foreach ($return as $row) {
    $value = check_plain($row-&gt;name).' '.check_plain($row-&gt;surname1).' '.check_plain($row-&gt;surname2);
    //$value = $row-&gt;name.' '.$row-&gt;surname1.' '.$row-&gt;surname2;
    $matches[$value] = $value;
  }

  // return for JS
  drupal_json_output($matches);
}


This works perfect. But I want that json return callback {nid; name} instead of {name,name}, and also show the name in textfield, but I can save nid in my form.

If I change to this my function ajax

$matches[$row-&gt;nid] = $value;


The previous sentence returns {nid, name}, but if I choose one value of the list name, in the textfield is shown the nid value, not the name value.

Any suggestions?
Take a look at the examples module's ajax_example_autocomplete.inc file. You'll need to add a validation function that looks up the nid from the node->title:

  $result = preg_match('/\[([0-9]+)\]$/', $title, $matches);
  if ($result &gt; 0) {
    // If $result is nonzero, we found a match and can use it as the index into
    // $matches.
    $nid = $matches[$result];
    // Verify that it's a valid nid.
    $node = node_load($nid);
    if (empty($node)) {
      form_error($form['node'], t('Sorry, no node with nid %nid can be found', array('%nid' =&gt; $nid)));
      return;
    }
  }
  // BUT: Not everybody will have javascript turned on, or they might hit ESC
  // and not use the autocomplete values offered. In that case, we can attempt
  // to come up with a useful value. This is not absolutely necessary, and we
  // *could* just emit a form_error() as below.
  else {
    $nid = db_select('node')
      -&gt;fields('node', array('nid'))
      -&gt;condition('title', db_like($title) . '%', 'LIKE')
      -&gt;range(0, 1)
      -&gt;execute()
      -&gt;fetchField();
  }