Changing Drupal's autocomplete path with JavaScript

Posted on July 18, 2012

Ever had an interface that needed an autocomplete field? Happens all the time - and Drupal makes that task trivial. But what if you need to change the autocomplete URL without reloading the page? Use these steps, and you'll find out how to do so with JavaScript.

For the purposes of this tutorial, we'll assume you don't care too much about the initial URL. So let's make it obvious that it's a placeholder. Let's start by declaring our menu entries.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
<?php      
function our_autocompleted_field_menu() {                                     
  $items = array();                                                           
  $items['our_autocompleted_field_form'] = array(                             
    'type' => MENU_CALLBACK,                                                  
    'access callback' => TRUE,                                                
    'page callback' => 'drupal_get_form',                                     
    'page arguments' => array('our_autocompleted_field_form'),                
  );                                                                          
  $items['our_autocompleted_field/autocomplete/%'] = array(                   
    'type' => MENU_CALLBACK,                                                  
    'access callback' => TRUE,                                                
    'page callback' => 'our_autocompleted_field_autocomplete',                
    'page arguments' => array(2),                                             
  );                                                                          
  return $items;                                                              
}

Now let's declare the form with our field. Like any other autocomplete field, we declare it by using the #autocomplete property on our form definition.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php                                                                               
function our_autocompleted_field_form() {                                     
  $form = array();                                                            
  $form['our_autocompleted_field_toggle'] = array(                                   
    // This is just a sample link to demonstrate the dynamic autocomplete URL.
    '#type' => 'markup',                                                      
    '#value' => '<a id="our-autocompleted-field-toggle" href="#">Toggle</a>', 
  );                                                                          
  $form['our_autocompleted_field'] = array(                                   
    '#type' => 'textfield',                                                   
    '#id' => 'our-autocompleted-field',                                       
    // Drupal needs a valid autocomplete path, otherwise it will not add the  
    // behavior. So we add the placeholder argument and replace that on the   
    // JS frontend.                                                           
    '#autocomplete_path' => 'our_autocompleted_field/autocomplete/PLACEHOLDER',
  );                                                                          
  return $form;                                                               
}

Now, let's define our autocomplete function. To demonstrate the dynamic capabilities, let's use the first argument - which comes along with the path - as a way to tell us whether to return results in lowercase or uppercase. Of course, you can use the dynamically-changed URL to vary your results however you want.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php      
function our_autocompleted_field_autocomplete($letter_case, $input) {         
  if ($letter_case == 'uppercase') {                                          
    $function = 'strtoupper';                                                 
  }                                                                           
  else {                                                                      
    $function = 'strtolower';                                                 
  }

  $matches = array(                                                           
    'Suggestion 1',                                                           
    'Suggestion 2',                                                           
  );                                                                          
  $matches = array_map($function, $matches);

  print json_encode($matches);                                                
  exit();                                                                     
}

Finally, we use a little bit of magic on the frontend to change the autocomplete path. The trick is to reload the autocomplete object that Drupal generates, otherwise, the change won't take effect. You also need to get rid of the old behavior - that way you avoid confusing duplicate calls. Find or create your module's JavaScript file. Then add the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$(document).ready(function() {                                                
  // ID format is {OUR-FIELD-ID}-autocomplete.                                  
  var autocompletePath = $('#our-autocompleted-field-autocomplete')           
                         .val().replace('/PLACEHOLDER', '');

  // Keep track of the case we're in.                                         
  var isUpperCase = false;

  $('#our-autocompleted-field-toggle').click(function() {                     
    if (isUpperCase) {                                                        
      var newURL = autocompletePath + '/lowercase';                           
      isUpperCase = false;                                                    
    }                                                                         
    else {                                                                    
      var newURL = autocompletePath + '/uppercase';                           
      isUpperCase = true;                                                     
    }                                                                         
    // Trick Drupal into rebinding the autocomplete behavior.                 
    $('#our-autocompleted-field-autocomplete').val(newURL)                    
    .removeClass('autocomplete-processed');

    $('#our-autocompleted-field').unbind().val('');                           
    Drupal.behaviors.autocomplete(document);

    return false;                                                             
  });

  // Simulate a click when initializing so that we have a valid autocomplete  
  // path.                                                                    
  $('#our-autocompleted-field-toggle').click();                               
});

And that's it. This code will toggle your autocomplete results between uppercase and lowercase. It's a contrived example, of course. But think of the possibilities!

Learning Drupal? Subscribe to my Drupal articles, tips and tutorials.

Comments

Erich SchulzMarch 11, 2013, 2:08 p.m.

Thanks for this. Are your two form elements supposed to have the same index?

Reply
silviogutierrezDec. 10, 2013, 5:45 p.m.

Fixed this. Thanks.

Reply
Omar FloresDec. 8, 2015, 4:06 p.m.

thanks very much for this, I'm running D7 and this excellent explanation you posted still works.

Reply
JackDec. 18, 2019, 12:42 p.m.

One of the best website for Drupal users as they can get here solution of problem which they face using Drupal language. IT users also very happy after getting this post whom I am serving dissertation writing services UK as by profession I am dissertation expert of leading academy Quality Dissertation in UK.

Reply
hillaryFeb. 22, 2019, 10:38 a.m.

Incredible post. Articles that have significant and savvy remarks are more agreeable, at any rate to me. It’s fascinating to peruse what other i need a dissertation individuals thought and how it identifies with them or their customers, as their point of view could help you later on.

Reply
RoweApril 14, 2019, 9:01 p.m.

There is nothing that I can do anything for assignment writers in uk. I guess that we will not be working on it as they are suggesting and we will be asked to do more things here for sure.

Reply
dsdsdMay 6, 2019, 5:53 a.m.

Bien qu’il n’y ait pas de schéma aléatoire aléatoire, cela peut vous aider à résoudre subtilement et à éviter les facteurs défavorables face aux situations d’urgence, et à saisir les facteurs favorables, afin que le personnel de vente des iwc montres ne puisse pas affecter l’activité en raison d’événements imprévus. Il peut même compter sur des situations imprévues pour inverser les inconvénients et faciliter les transactions. Pour exercer efficacement leur propre résilience, le personnel de vente ne peut pas agir conformément aux règles du processus de vente, jaeger lecoultre montres mais doit apprendre à découvrir de nouvelles situations, de nouveaux problèmes et à résumer les nouvelles expériences tirées du processus de vente.

Reply
CherisseMay 15, 2019, 9:22 p.m.

Well, I don’t have much to say about www.imfaceplate.com/gluecksspielmaster/rubbellose-sind-wieder-populr. But it was a good article and I liked reading it. Would like to see more from them.

Reply
fggfggfMay 18, 2019, 2:28 p.m.

Dans le processus de vente, il n’est pas difficile pour le vendeur d’obtenir la confiance du client: il suffit de laisser le client penser que vous le servez sincèrement et que votre produit ou votre service est vraiment ce dont il a besoin. Il suffit de lui laisser une attente sincère pour vous. Tant que vous pouvez atteindre un consensus avec le client est suffisant. replique montre de luxe Les clients ont les yeux vifs et leurs sentiments sont aussi très vifs. Vos mots, un regard, un geste, ils sont tous dans le cœur. Un bon vendeur. Il faut toujours faire passer les intérêts des clients en premier. Avec ce genre d’attitude au travail, je pense que même les clients les plus difficiles seront conquis.

Reply
gfdJune 25, 2019, 10:03 a.m.

粉嫩公主酒酿蛋的效果有丰胸产品这么神奇吗?那你必须了解一下粉嫩公主酒酿蛋的丰胸原理了,你就知道了。粉嫩公主酒酿蛋经过现代科学配比丰胸产品粉嫩公主有机结合后能够迅速被人体吸收,依靠提供与女性自身分泌雌性激素高度同源的酒酿中含的醣化酵素来激发女性的酒酿蛋丰胸雌性症状,从而促进乳腺及乳房周围细胞的增长及再次发育,一方面通过促进乳头的乳腺管道的加长和不断分支,来增强乳腺组织的发育,粉嫩公主丰胸产品并有效的帮助乳房的增大。粉嫩公主酒酿蛋丰胸解开女人的幸福密码!

Reply
David TranJuly 17, 2019, 7:05 p.m.
Reply
John diskJuly 23, 2019, 6:47 a.m.

Such a great post. I am glad to be here and read this greengeeks coupon code wonderful post. I have read a few articles on your website and I really like your style.

Reply
KrausAug. 21, 2019, 11:58 a.m.

Ready to play Fortnite Battle Royale on your Android device? Fortnite hacks

Reply
Sumitsingh72Aug. 24, 2019, 7:41 a.m.

Shiftinindia Packers and Movers Delhi is the solid and expert movers and packers local time in pune , packers and movers company , moving cost estimator calculator , packers and movers Pune charges

Reply
molly jonesSept. 25, 2019, 10:07 a.m.

A story covering can definitely change a living and working space – it might be an impression of the subject, organizing and pulling together various parts of a room or having a solid effect.

To guarantee your floor covering is absolutely legitimately for your space, the size, concealing, and arrangement ought to be picked circumspectly. It's an individual choice that requires fitness and course. Our cultivated gathering of floor covering makers in Dubai will oversee all of you through the system to make an understanding of your arrangement into a stunning mat.

Material

Wool floor covers have reliably been and reliably will be in style. In any case, as development progress, so homes complex subject. We, at Carpets in dubai, are happy to offer you a wide extent of (the latest?) tones and materials including our choice quality 100% New Zealand Wool, Bamboo Viscose, Rayon Viscose, Tencel, Japanese Acrylic, and Nylon.

Advancement Techniques

Floor covers are made by hovering yarn through a touch of help material. These circles can change in thickness, height, and cut generally called the floor covering pile. The floor covering pile can influence basically the vibe and nearness of a carpet. The most generally perceived load types are the luxurious extreme stack, the fragile and everlasting cut-pile, and the intense and current circle store.

Reply
Targeted Web TrafficOct. 9, 2019, 2:05 a.m.

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! Targeted Web Traffic

Reply
TYHEROct. 10, 2019, 10:48 a.m.

You have beaten yourself this time, and I appreciate you and hopping for some more informative posts in future. Thank you for sharing great information to us. https://ozbassforum.com/viewtopic.php?t=21277&start=2265

Reply
remembrance sunday poemsOct. 11, 2019, 3:03 a.m.

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! remembrance sunday poems

Reply
IDN PokerOct. 11, 2019, 4:04 p.m.

Kronospoker Situs Judi Online, IDN Poker, IDN Poker Mobile, Agen Poker Terpercaya Indonesia untuk permainan Poker Online, Domino Qiu Qiu, Ceme Keliling, Capsa Susun dan Super10

Reply
afiya aliOct. 13, 2019, 1:37 a.m.

Nice post. I was checking constantly this blog and I am impressed! Extremely helpful information specially the last part I care for such info a lot. I was seeking this particular information for a very long time. Thank you and good luck. remembrance sunday prayers

Reply
Jessica JonesOct. 15, 2019, 5:32 a.m.

I was surfing the Internet for information and came across your content post. I am impressed by the information you have on this article and Many many thanks for this info :) essay assignment help london - nursing assignment writers - help with marketing assignment - mba assignment writing service - accounting assignment writers

Reply
https://cafequenteesherlock.blogspot.com/2014/12/Oct. 17, 2019, 3:02 a.m.

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! https://cafequenteesherlock.blogspot.com/2014/12/

Reply
afiya aliOct. 18, 2019, 5:39 a.m.

Thanks for picking out the time to discuss this, I feel great about it and love studying more on this topic. It is extremely helpful for me. Thanks for such a valuable help again. http://blogjornalsinaculo.blogspot.com/2013/07/caetano-veloso-atracao-mais-esperada-do.html

Reply
aromatherapy gift ideasOct. 19, 2019, 4:47 p.m.

You have beaten yourself this time, and I appreciate you and hopping for some more informative posts in future. Thank you for sharing great information to us. aromatherapy gift ideas

Reply
plants nurseryOct. 21, 2019, 3:07 a.m.

You have beaten yourself this time, and I appreciate you and hopping for some more informative posts in future. Thank you for sharing great information to us. plants nursery

Reply
http://ftls.org/fr/a-gratuit/divertissement-loisirs/webcams/Oct. 22, 2019, 2:14 a.m.

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! http://ftls.org/fr/a-gratuit/divertissement-loisirs/webcams/

Reply
james thomasOct. 23, 2019, 7:29 a.m.

What your stating is absolutely accurate. I know that everyone have to say the identical factor, but I just feel that you put it in a way that absolutely everyone can realize. I also really like the photographs you set in right here. They fit so effectively with what youre hoping to say. Im sure youll achieve so numerous men and women with what youve acquired to say. 안전놀이터

Reply
afiya aliOct. 25, 2019, 2:48 a.m.

What a sensational blog! This blog is too much amazing in all aspects. Especially, it looks awesome and the content available on it is utmost qualitative. http://www.equipyrene.com/dun/favos.htm

Reply
Lisa TaylorOct. 25, 2019, 8:25 a.m.

Great blog design. I like to follow your creative ideas in blogging. If you are looking for high-quality text on any topic, we https://breakingnewgrounds.org/ will help you at any time of the day quickly and efficiently. Keep delighting us with new posts!

Reply
thermomixOct. 31, 2019, 2:11 a.m.

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! https://www.amourdecuisine.fr/article-pates-a-creme-de-courgettes-thermomix.html

Reply
afiya aliNov. 2, 2019, 4:49 p.m.

This type of message always inspiring and I prefer to read quality content, so happy to find good place to many here in the post, the writing is just great, thanks for the post. https://www.rosenoisettes.com/2016/03/smoothie-bowl-la-fraise-kiwi-et-ananas.html

Reply
https://retrogralnia.pl/kalendarium/Nov. 4, 2019, 1:44 p.m.

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! https://retrogralnia.pl/kalendarium/

Reply
afiya aliNov. 7, 2019, 1:29 a.m.

Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks http://www.prw.pl/articles/view/23982/Polcon-2012-najwieksze-swieto-milosnikow-fantastyki

Reply
afiya aliNov. 11, 2019, 11:47 p.m.

Thank you so much as you have been willing to share information with us. We will forever admire all you have done here because you have made my work as easy as ABC. http://www.paranormalne.pl/topic/30698-polcon-2012/

Reply
afiya aliNov. 13, 2019, 12:05 a.m.

I recently found many useful information in your website especially this blog page. Among the lots of comments on your articles. Thanks for sharing. http://www.otopaczkow.pl/news.php?id=74487&tytul=zbliza-sie-polcon-2012

Reply
afiya aliNov. 17, 2019, 6:32 a.m.

Remarkable article, it is particularly useful! I quietly began in this, and I'm becoming more acquainted with it better! Delights, keep doing more and extra impressive! http://itf.fys.kuleuven.be/~toine/wwwadres.htm

Reply
RadioNov. 18, 2019, 2:29 p.m.

Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for. http://www.histoiredesmedias.com/+-Radio-TV-+.html

Reply
afiya aliNov. 22, 2019, 5:39 a.m.

I am happy to find your distinguished way of writing the post. Now you make it easy for me to understand and implement the concept. Thank you for the post. http://szczepienie.blogspot.com/2015/09/cesarskie-ciecie-porod-naturalny-flora.html

Reply
Callen LoftiesNov. 22, 2019, 4:07 p.m.

Hello there once again I must say it was a genuinely fine adventure for me personally when I visited your web site. I just needed to praise you on the excellent quality of the work you've accomplished here and to send your team all the best with everything as you develop into the future. It was a hoot to look through your internet site and I'll undoubtedly be stopping by once more to see how you're doing. Thanks a lot and with luck I'll doubtless see you here in a little while - Callen Lofties

Reply
Alby LoftwareNov. 22, 2019, 4:09 p.m.

Hi folks again I must say it was a great experience for me personally when I checked out your top notch web site. I hope you don't mind if I congratulate you on the quality of the work you have accomplished here and additionally to wish you good luck with it as you proceed going forward. It was a hoot to check out your website and I shall probably be stopping by again soon to find out exactly how you are getting on. Thanks a bunch and if luck is on my side I shall doubtless see you here again very soon - Alby Loftware

Reply
bokNov. 29, 2019, 9:33 a.m.

I will have to follow you, the information you bring is very real, reflecting correctly and objectively, it is very useful for society to grow together. enable flash in chrome

Reply
Charles CookeDec. 3, 2019, 4:52 a.m.

For those looking to come on two feet (or even two wheels), there are seasonal passenger ferries from Ballycastle to the beautiful island of Islay and the port at Campbeltown on the Kintyre Peninsula in Argyll. emergency minibus hire minibus hire glasgow minibus hire kent cheap minibus coach hire minibus hire blackpool

Reply
amanda cerny feetDec. 9, 2019, 10:42 a.m.

Hi, Great Post !! Thanks for sharing useful information your tips this is very helpful for me.....Keep writing.....

amanda cerny feet

Reply
amanda cerny tv showsDec. 9, 2019, 10:42 a.m.

Hi, Great Post !! Thanks for sharing useful information your tips this is very helpful for me.....Keep writing..... amanda cerny tv shows

Reply
Lynda WilliamDec. 12, 2019, 8:02 a.m.

I am looking at this theme any famous blog, however, at least I am getting it this subject on your blog genuinely your blog essayist are astounding composing style and article idea I am so similar to it in your article. Emergency Dental Care Tulsa

Reply
GaborDec. 23, 2019, 8:18 a.m.

It is free to copy text faces like lenny face memes

Reply
QuickBooks Helpline NumberDec. 28, 2019, 8:55 p.m.

QuickBooks is a feature reach accounting software that is developed to assist you in accounting and payroll tasks. Users can call us at QuickBooks Helpline Number @ +1-8OO-381-6493 to get their software problems resolved instantly by experts. Our comprehensive range of QuickBooks support services consists of QuickBooks software installation, upgrade, financial data management support, troubleshooting, fixing QuickBooks issues & errors, assistance for printing and integration support, etc. Read more: QuickBooks Helpline Number QuickBooks Helpline Number QuickBooks Helpline Number QuickBooks Helpline Number

Reply
sophieJan. 2, 2020, 3:05 a.m.

I would like to say that this blog really convinced me to do it! Thanks, very good post. Go to site instastalker to know mlore wonderful hashtag on instagram.

Reply
Rosa WilliamJan. 9, 2020, 7:12 a.m.

you've got some interesting points in this article. I would have never considered any of these if I didn’t come across this. Thanks!. Custom Printed Boxes

Reply

Post New Comment