Reputation: 2539
I'm using the jquery autocomplete plugin that comes with the symfony sfFormExtra plugin.
/*
* jQuery Autocomplete plugin 1.1
*
* Copyright (c) 2009 Jörn Zaefferer
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* Revision: $Id: jquery.autocomplete.js 15 2009-08-22 10:30:27Z joern.zaefferer $
*/
It does seem to sort json results according to the key, but I can't find any mention of sort options in the code.
I would like the results sorted like returned from the server.
The results are build like this
public function doMemberSelectForSelectById($q, $limit){
$query = $this->retrieveMemberOrganisations($this->createUnrestrictedQuery('o'))->
andWhere("o.name like '%".$q."%'")->
orderBy("o.name")->
limit(intval($limit));
$org_data = $query->execute();
$orgs = array();
foreach ($org_data as $org){
$orgs[$org->getId()] = $org->getName();
}
return $orgs;
}
$orgs = Doctrine_Core::getTable('Organisation')->
doMemberSelectForSelectById($request->getParameter('q'), $request->getParameter('limit'));
echo $this->renderText(json_encode($orgs));
}
return sfView::NONE;
The result in Chrome Dev Tools is (ordered by name)
{
"1781": "1st Mechanical \/ 1st Maintenance",
"1771": "Acco Building Ltd",
"203": "Active Welding Limited",
"443": "Aircon Commissioning & Services Ltd",
"588": "Akon Electrical Engineering Limited",
"625": "Alaska Interiors Ltd",
"796": "Alutech Windows & Doors Ltd",
"584": "Arrow International Ltd"....
}
The javascript that triggers it is here
jQuery(document).ready(function() {
jQuery("#autocomplete_rsvpCompany1").focus(function({
jQuery(this).val('');});
jQuery("#autocomplete_rsvpCompany1").autocomplete(
'http://www.nzgbc.org.nz/index.php?option=com_nzgbc_member&uri=%2Forganisation%2FjsonListMember%2Faction',
jQuery.extend({}, {
dataType: 'json',
minChars: 0,
delay:0,
max:700,
scroll: true,
parse: function(data) {
var parsed = [];
for (key in data) {
parsed[parsed.length] = { data: [ data[key], key ], value: data[key], result: data[key] };
}
return parsed;
}
}, { })
).result(function(event, data) {
jQuery('#rsvpCompany1').val(data[1]);
});
How can I achieve this?
Upvotes: 1
Views: 805
Reputation:
You should change the "parse" method as follows:
parse: function(data) {
var parsed = [];
for (key in data) {
parsed[parsed.length] = {
data: [ data[key], key ],
value: data[key],
result: data[key]
};
}
parsed.sort(function (a, b){
var aKey = a.value;
var bKey = b.value;
return ((aKey < bKey) ? -1 : ((aKey > bKey) ? 1 : 0));
});
return parsed;
}
The problem is that the "data" array has a numeric key, so when you loop over the "data" elements in your "for" loop, you are adding the elements to the "parsed" array in the numeric order (eg.: 203, 443, 584, 588, etc.), so after adding all the elements to the "parsed" array you have to sort it by "data[key]", and not by "key".
Upvotes: 1