Skip to content

Instantly share code, notes, and snippets.

@morshedalam
Last active March 7, 2017 10:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save morshedalam/8974743 to your computer and use it in GitHub Desktop.
Save morshedalam/8974743 to your computer and use it in GitHub Desktop.
AutoComplete using CakePHP and JQuery
public function autocomplete($conditions = array(), $id = 'id', $label = 'name', $value = 'name')
{
$responses = array();
$rows = $this->find('all', array(
'conditions' => $conditions,
'fields' => array(
"{$id}",
"{$label}",
"{$value}",
)
));
$i = 0;
foreach ($rows as $row) {
$responses[$i]['id'] = $row[$this->name][$id];
$responses[$i]['label'] = $row[$this->name][$label];
$responses[$i]['value'] = $row[$this->name][$value];
$i++;
}
return $responses;
}
var completer = null;
$(".auto-complete").autocomplete({
source: generateUrl(),
minLength: 2, //This is the min amount of chars before auto complete kicks in
autoFocus: true,
type: 'json',
select: function (event, ui) {
$('#' + parent.completer.attr('data-id-map')).val(ui.item.id)
}
});
var generateUrl = function () {
return function (request, response) {
parent.completer = $(this.element);
var url = parent.completer.attr('data-url') + '/term:%s',
param_field = parent.completer.attr('data-param');
url = url.replace('%s', encodeURIComponent(request.term));
if (param_field !== undefined) {
url += '/' + param_field + ':' + $('#' + param_field).val();
}
console.log(url);
return $.get(url, response, 'json');
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment