Skip to content
cm-t edited this page Nov 6, 2012 · 4 revisions

** Work in progress**

Example with multiple select with remote data

Customize your jquery.jqGrid-4.4.1.js

Add a formatter for the grid

Before $.fn.fmatter.link = function(cellval, opts) { close to line 5115, add the following code:

$.fn.fmatter.select2remotemultiple =function(cval, opts) {
	var op = $.extend({},opts.checkbox), ds;
	if(opts.colModel !== undefined && !$.fmatter.isUndefined(opts.colModel.formatoptions)) {
		op = $.extend({},op,opts.colModel.formatoptions);
	}
	if(op.disabled===true) {ds = ""; "disabled=\"disabled\"";} else {ds="";}
	if($.fmatter.isEmpty(cval) || $.fmatter.isUndefined(cval) ) {cval = $.fn.fmatter.defaultFormat(cval,op);}
	cval=cval+"";cval=cval.toLowerCase();
	return "<input type=\"hidden\" class=\"select2remotemultiple\" value=\""+ cval+"\" offval=\"no\" "+ds+ "/>";
};

Add a formatter for edit

( TODO )

jqGrid settings

In your page.html where you set jqGrid, be aware to have in the colModel the new formatter and the loadComplete function to call to build select2:

$(function() {
  $("#list").jqGrid({
    url:'json_search.php',
    editurl: 'ajax_mod.php',
    datatype: 'json',
    mtype: 'GET',
    height: "300px",
    colNames:[(...) 'moa'],
    colModel :[ 
(...) 
      {name:'moa', index:'a.moa', align:'left', sortable: false,
	      		editable:true, edittype:"select2remotemultiple",formatter: 'select2remotemultiple',
	      		formoptions:{ rowpos:4, label: "Responsable MOA"},editrules:{required:false} }
],
(...)
    loadComplete:doSelect2, // call the select2 builder when a load is performed
(...)

Select2 init

This function will be called every time a page/scroll is performed. Note initSelection

function doSelect2(){
    $('.select2remotemultiple').select2({
	minimumInputLength: 1,
        placeholder: 'No MOA',
        width: 100,
        hright: 24,
        multiple: true,
        ajax: {
            url: "inc/ajax/ajax_user.php",
            dataType: 'json',
            quietMillis: 100,
            data: function (term, page) {
                return {
                    term: term, //search term
                    page_limit: 10 // page size
                };
            },
            results: function (data, page) {
                return { results: data.results };
            }

        },
        initSelection: function(element, callback) {
        	return $.getJSON("inc/ajax/ajax_user.php?q=" + (element.val()), null, function(data) {
// the remote script will return something like [{id: "CA", text: "California"},{id:"MA", text: "Massachusetts"}] without the result key
        		return callback(data);
			});
        	 /* testing
                    var data = [{id: "CA", text: "California"},{id:"MA", text: "Massachusetts"}];
	            return callback(data);*/
        }
    });

How it looks

In situ: select2 with jqGrid