Autocomplete field where title is replaced with NID I'm using Drupal 7 and I have made autocomplete function to be called on a field.
File my_module.module:
&lt;?php    

function my_module_menu() {
        
    $items = array();

    $items['/autocomplete'] = array(
        'title' =&gt; 'Autocomplete',
        'page callback' =&gt; 'companyAutocomplete',
        'access arguments' =&gt; array('autocomplete'),
        'type' =&gt; MENU_LOCAL_TASK,
        'weight' =&gt; 1,
        'file' =&gt; 'my_module.autocomplete.inc'
    );   
       
    return $items;
}

File my_module.autocomplete.inc:
&lt;?php

function companyAutocomplete($fieldInput) {

    $returnArray = array();

    $query = db_select('node', 'n')
        -&gt;fields('n', array('nid', 'title'))
        -&gt;condition('n.title', '%'.db_like($fieldInput).'%', 'LIKE')
        -&gt;condition('n.type', 'company', '=')
        -&gt;orderBy('n.title', 'ASC')
        -&gt;range(0, 10);

    // print strtr((string) $query, $query-&gt;arguments());

    $results = $query-&gt;execute();

    foreach ($results as $result) {
        $returnArray[$result-&gt;title] = check_plain($result-&gt;title);
    }

    drupal_json_output($returnArray);
}

File template.php:
&lt;?php

function my_theme_preprocess_field(&amp;$vars) {

    if ($node = menu_get_object()) {

        if ($node-&gt;type == 'company') {

            if ($vars['element']['#field_name'] == 'field_company') {
                $company = entity_metadata_wrapper('node', $vars['items']['0']['#markup']);
                $vars['items']['0']['#markup'] = $company-&gt;label();
            }
        }
    }
}

and I have a field company (I use this field to enter NID):
$form['field_company'] = array(
    '#type' =&gt; 'textfield',
    '#default_value' =&gt; $defaultCompany,
    '#title' =&gt; 'Company',
    '#autocomplete_path' =&gt; '/autocomplete',
);

When I type something in field, autocomplete returns correct text value of the searched term and that is ok.
How can I modify companyAutocomplete() function or the field itself for autocomplete to works as it is, but to write NID instead title in $form['field_company']['und'][0]['value']?
You need the array keys to be nids, so change it to
$returnArray[$result-&gt;nid] = check_plain($result-&gt;title);