9 novembre 2013

dojo autocomplete (suggest box)

CLIENT



(html)



<input id="mySuggestBox" />



(javascript dojo v.1.9):



require([
    "dojo/_base/declare",
    "dojox/data/QueryReadStore",
    "dijit/form/ComboBox",
    "dojo/domReady!",

], function(declare, QueryReadStore, ComboBox) {


var AutocompleteStore = declare(QueryReadStore, {

    fetch: function(request){
        request.serverQuery = {q:request.query.name};
        return this.inherited("fetch", arguments);
    },
    wrapItem: function(rawItem, callback){
        this._xhrFetchHandler({
                identifier:'id',
                items: [rawItem],
                label: 'label'
            },
            {},
            function(items){ 
                callback(items[0]); 
            }
        );

    }
});
var store new AutocompleteStore({url:'services/myservice.php'});
var cb = new ComboBox({

        store: store,
        searchAttr: "name",
        labelAttr: "label",
        autoComplete: true,
        onChange: function(){  if(!this.item)  this.set("displayedValue", "");  }
  }, "mySuggestBox");

  //set default value

  store.wrapItem({id:111, name:"lorem", label: "ipsum"}, function(item){ 
       cb.set("item", item);
  });

 });



SERVER


(myservice.php):

<?php
$q = $_GET["q"];
$sql = "SELECT field_id AS id, field_xxx AS name, CONCACT('<b>',field_xxx,'</b')" AS label FROM myTable WHERE field_xxx LIKE "%{$q}% ORDER BY field_xxx LIMIT 10";
//fetch query... :
/*
$fields = array(
    array (id=>1, name=>"lorem", label=> "<span>lorem</span>",
    array (id=>2, name=>"ipsum", label=>"<span>impsum</span>", 
   ....
);
*/
header("Content-Type", "text/json");
echo json_encode(array('numRows'=>count($fields), 'items'=>$fields, 'identity'=>'id'));

Nessun commento:

Posta un commento