0

I'm using Drupal 7 and I have made autocomplete function to be called on a field.

File my_module.module:

<?php    

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

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

File my_module.autocomplete.inc:

<?php

function companyAutocomplete($fieldInput) {

    $returnArray = array();

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

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

    $results = $query->execute();

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

    drupal_json_output($returnArray);
}

File template.php:

<?php

function my_theme_preprocess_field(&$vars) {

    if ($node = menu_get_object()) {

        if ($node->type == 'company') {

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

and I have a field company (I use this field to enter NID):

$form['field_company'] = array(
    '#type' => 'textfield',
    '#default_value' => $defaultCompany,
    '#title' => 'Company',
    '#autocomplete_path' => '/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']?

0

1 Answer 1

0

You need the array keys to be nids, so change it to

$returnArray[$result->nid] = check_plain($result->title);
1
  • 1
    attention: showed up in LQP queue ... Nov 8, 2020 at 11:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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