Drupal 7 - Override JS cache from`Drupal.ACDB.prototype.search`

By k, 28 July, 2020

Authored on

Tue, 07/28/2020 - 20:25
Image

The javascript autcomplete feature in Drupal 7 is very useful, but sometimes you might need to make some tweaks there. Here I will give a brief description how I remove the cache from the AutoComplete DataBase object (`Drupal.ACDB`).

I wrote a Javascript behavior and it looks like this:

(function ($) {
	Drupal.behaviors.removeAutocompleteCache = {
	    attach: function (context) {
	        /**
	         * Override client-side search function.
	         */
	        var searchCallback = Drupal.ACDB.prototype.search;
	        Drupal.ACDB.prototype.search = function (searchString) {
	            this.cache = {};
	            searchCallback.apply(this, [searchString]);
	        };

	        // Unbind the behaviors to prevent multiple search handlers
	        $("#ID-AUTOCOMPLETE-ELEMENT")
	            .unbind("keydown")
	            .unbind("keyup")
	            .unbind("blur");
	        $("#ID-AUTOCOMPLETE-ELEMENT-HIDDEN")
	            .removeClass("autocomplete-processed");

	        // Rebind autocompletion with the new code
	        Drupal.behaviors.autocomplete.attach(context);
		}
	};
})(jQuery);

The first step is to make a copy of the original search function, It's being stored into `searchCallback` function variable. After that the actual overwrite happens where it just reset the cache attribute from current objet and invoke the original function by using `.apply()` because it allows to send the current `this` object as first parameter.

The other steps are self-explanatory, it will remove the autocomplete feature from the current element which needs a new behavior. In order to do that it's required to unbind the original listerners plus remove the "autocomplete-processed" CSS class from the sibling hidden element  of the actual autocomplete search input.

Then finally the autocomplete behavior is invoked once again manually in order to inject our new behavior since it was already altered into current JS behavior.

It should be enough to avoid the cache from the autocomplete JS behavior.

A funny fact, few years ago I faced a similar case in some sort of way, where I found another way to do something similar, however it looks like the coding from the old me is a little bit different. Long story short, I wrote it in Spanish, if you want to take a look it's available here: http://www.7sabores.com/blog/sobrescribir-script-auto-completado-drupal-7

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.