Skip to content

Instantly share code, notes, and snippets.

@cAstraea
Last active April 14, 2016 15:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cAstraea/7c1797d466ae5cb91aa48a7a4108d40a to your computer and use it in GitHub Desktop.
Save cAstraea/7c1797d466ae5cb91aa48a7a4108d40a to your computer and use it in GitHub Desktop.
Typeahead for previously used values for sugarcrm fields using localstorage
({ extendsFrom: 'RecordView', // extendsFrom: 'CreateView',
myEvents: {
'focusin [name=ca_autocompl_c]': 'typeahead',
},
initialize: function(options) {
this._super('initialize', [options]);
this._addJavascript('https://code.jquery.com/ui/1.8.9/jquery-ui.min.js');
this._addCssCustom('https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.css');
if (this.events) {
// Extend events hash with my events if one already exists
_.extend(this.events, this.myEvents)
} else {
// Otherwise, just use my events
this.events = this.myEvents;
}
},
_addJavascript: function (jsrc,pos) { //https://community.sugarcrm.com/message/56341#47410
pos = typeof pos !== 'undefined' ? pos : 'head';
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsrc);
th.appendChild(s);
},
_addCssCustom: function (jsrc,pos) {
pos = typeof pos !== 'undefined' ? pos : 'head';
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('link');
s.setAttribute('rel','stylesheet');
s.setAttribute('href',jsrc);
th.appendChild(s);
},
typeahead:function(){
if(localStorage.getItem("ac_source") === null){
var autocomp = new Array();
localStorage.setItem("ac_source", JSON.stringify(autocomp));
}
var source = JSON.parse(localStorage.getItem('ac_source'));
disable=false;
$( "input[name='ca_autocompl_c']" ).autocomplete({
source: source,
minLength: 1,
select: function(event, ui) {
$( "input[name='ca_autocompl_c']" ).val(ui.item.label);
},
open: function(event, ui) { disable=true },
close: function(event, ui) {
disable=false; $(this).focus(); },
// mustMatch implementation
change: function (event, ui) {
if (ui.item === null) {
$(this).val('');
$( "input[name='ca_autocompl_c']" ).val('');
}
}
}).blur(function(){
if(!disable){
var retrievedData = localStorage.getItem("ac_source");
var mReplace = JSON.parse(retrievedData);
if ($( "input[name='ca_autocompl_c']" ).val() !== "") {
mReplace.push($.trim($( "input[name='ca_autocompl_c']" ).val()));
localStorage.setItem("ac_source", JSON.stringify(_.uniq(mReplace)));
}
}
});
// mustMatch (no value) implementation
$("#field").focusout(function() {
if ($( "input[name='ca_autocompl_c']" ).val() === '') {
$( "input[name='ca_autocompl_c']" ).val('');
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment