Last active
March 7, 2017 10:14
-
-
Save morshedalam/8974743 to your computer and use it in GitHub Desktop.
AutoComplete using CakePHP and JQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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