
knackforge
October 28, 2014
Autocomplete is a feature for textfields in Drupal. It provides a dropdown list of matching options from the server. It is implemented through AJAX. To know how to add an autocomplete form element in Drupal visit https://www.drupal.org/node/854216
For customizing autocomplete we need to override the Drupal system file "misc/autocomplete.js". This can be achieved ideally in two ways:
function MY_MODULE_js_alter(&$javascript) {
$javascript['misc/autocomplete.js']['data'] = drupal_get_path('module', 'MY_MODULE') . '/js/autocomplete.js';
}/** * Performs a cached and delayed search. */
Drupal.ACDB.prototype.search = function (searchString) {
var db = this;
this.searchString = searchString;
// See if this string needs to be searched for anyway.
searchString = searchString.replace(/^\s+|\s+$/, '');
if (searchString.length <= 0 || searchString.charAt(searchString.length - 1) == ',') {
return;
}
// See if this key has been searched for before.
if (this.cache[searchString]) {
return this.owner.found(this.cache[searchString]);
}
// Initiate delayed search.
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(function () {
db.owner.setStatus('begin');
// Ajax GET request for autocompletion. We use Drupal.encodePath instead of // encodeURIComponent to allow autocomplete search terms to contain slashes.
$.ajax({
type: 'GET',
url: db.uri + '/' + Drupal.encodePath(searchString),
dataType: 'json',
success: function (matches) {
if (typeof matches.status == 'undefined' || matches.status != 0) {
db.cache[searchString] = matches;
// Verify if these are still the matches the user wants to see.
if (db.searchString == searchString) {
db.owner.found(matches);
}
db.owner.setStatus('found');
}
},
error: function (xmlhttp) {
alert(Drupal.ajaxError(xmlhttp, db.uri));
}
});
}, this.delay);
};Now we tweak the traits of autocomplete one by one:
db.cache[searchString] = matches;
ii. Flush cache
jQuery("#autocomplete_ElementName").result(function() {
jQuery("#autocomplete_ElementName").flushCache();
});if (searchString.length < Min || searchString.charAt(searchString.length - 1) == ',')
this.delay = 'time_in_milliseconds';
dataType: 'jsonp',
searchString = searchString + "/" + $("#otherfield").val();
Just like how your fellow techies do.
We'd love to talk about how we can work together
Take control of your AWS cloud costs that enables you to grow!