Quel est le plugin tableur le plus abouti utilisable avec jQuery ?

Selon l'article jQuery, il semblerait que jqGrid soit le plus aboutit, voici donc quelques notes au sujet de jqGrid.

jqGrid

jqGrid is an Ajax-enabled JavaScript control that provides solutions for representing and manipulating tabular data on the web.

jqGrid est un ensemble de contrôles JavaScript Ajax qui fournit des solutions pour représenter et pour manipuler des données tabulaires sur le web.

  • Un PDF jqGrid Version 3.4 Released February 2009 (Obsolète)

Liens jqGrid en vrac

  • How it Works
  • jqGrid ColModel API
    • index : string Set the index name when sorting. Passed as sidx parameter. empty string
    • jsonmap : string Defines the json mapping for the column in the incoming json string. See Retrieving Data
    • name : string Set the unique name in the grid for the column. This property is required. As well as other words used as property/event names, the reserved words (which cannot be used for names) include subgrid, cb and rn.
  • JSON Data

Voyez l'exemple de l'édition des éléments de la table via un formulaire : Edit row - add dialog for data editing.

Appliquer les paramètres par défaut à toutes vos grilles

$.jgrid.default  array  This array is used to define a grid option common to all 
jqGrids in the application. Typically, this is called once to 
set the default for one or more grid parameters -- any 
parameter can be changed. Typical implementation; 
$.extend($.jgrid.defaults,{rowNum:10})

Activer la sélection multi lignes, la coloration alternative d'une ligne sur 2 et une largeur maximale auto dimensionnée

var mygrid = jQuery("#liste").jqGrid({ 			
		altRows: true, // Colorie une ligne sur 2
		autowidth: true, // Largeur automatique (100%)
		height: "100%", // Hauteur maximale (100%) et dépends du contenu (le nombre de lignes dynamiques)
		multiselect: true, // Sélection multiple

Sélectionner des lignes, connaitre le nombre de lignes, lire les données des lignes

Voyez getGridParam avec les jqGrid Options

Connaitre le nombre de ligne de votre tableau

var numberOfRecords = $("#liste").getGridParam("records");

Connaitre les lignes sélectionnées dans votre tableau

var selectedItems = $("#liste").getGridParam("selarrrow");

Lire les données d'une ligne de votre tableau

var id = selectedItems[0]; // Première ligne sélectionnée
var rowData = jQuery("#liste").jqGrid('getRowData',);

Communiquer en JSON avec jqGrid

Utilisation d'un flux JSON mappé (jsonmap)

using named JSON

You can use dotted names in the colModel definition ('cell.Title', 'cell.Creator' etc.) like it documented in http://www.trirand.com/jqgridwiki/d.... Another way is using of jsonmap see http://stackoverflow.com/questions/... for an example.

En gros si 'arf' est la donnée contenue dans le Json :

{"page":1,"total":1,"records":1,"rows":[{"id":13,"arf":"arfvaluez","cell":[13,"2007-10-06","Client 3","1000.00","0.00","1000.00",null]},{"id":13,"arf":"arfvaluez","cell":[13,"2007-10-06","Client 3","1000.00","0.00","1000.00",null]}]}
// Vous avez le choix entre :
			colModel:[ 
//			          	{name:'total',index:'total', width:80, align:"right"},
//			          	{name:'arf',index:'total', width:80, align:"right" /*,  jsonmap:'arf'*/}, 
			          	{name:'arfautre',index:'total', width:80, align:"right", jsonmap:'arf'},
//			          	et les autres colonnes...

Recherche avec jqGrid

Pour la recherche, vous avez 3 choix :

Recherche inline : toutes les colonnes visibles sont recherchables

Envoi les noms de colonne en GET

_search	true
monNomDeCol	maRecherche

Recherche simple : recherche sur une seule colonne

Envoi 3 champs en GET

searchField	monNomDeCol
searchOper	eq
searchString	maRecherche

Recherche multiple : vous pouvez combiner des filtres de recherche sur toutes les colonnes

Envoi les filtres en GET au format JSON

_search	true
filters	{"groupOp":"AND","rules":[{"field":"monNomDeCol","op":"eq","data":"maRecherche"},{"field":"date_inscription","op":"eq","data":"14/10/2010"}]}

La recherche multiple :

jQuery("#liste").jqGrid('navGrid','#pagerListe',
			{
				edit:false,add:false,del:false,search:true,refresh:true
			},
			{}, // edit options
			{}, // add options
			{}, // del options
			{multipleSearch:true} // search options
			{} // view options
			);

FormEdit

Identifier l'enregistrement en cours et envoyer sa valeur

Lors de l'édition, création suppression d'une entrée de votre tableau, jqGrid ajoute deux paramètres lors de l'appel de votre serveur :

  • id ( le rowid autocalculé ou dépendant si une colonne à une clef primaire)
  • oper (l'opérateur : add,edit,del)
Note the id attribute in the <row> tags. While this attribute can be omitted, it is a good practice to have 
a unique id for every row. If this attribute is omitted, jqGrid has two ways of dealing with need for 
unique ids: 
1.  if the property key in the colModel is set to true for a particular column, then jqGrid will assign 
the value of this column to be the id of the row; otherwise, 
2.  jqGrid sets the row id based on the order of the row.  
If you are using a content-free primary key to identify your data rows, then do not include this value 
in the grid as a visible cell; instead, include it in the query and pass it as the row id attribute. It will 
always be available for jqGrid and even jQuery operations but not be visible on the page.
colModel:[
			{name:'table_id', index:'table_id', width:15, align:"center",
//				editable:false
				// Pour l'envoyer dans le form, il faut editable:true obligatoirement ! Et pour le pouvoir l'éditer, il faut le cacher avec hidden:true 
//				editable:true,
//				hidden:true
//				hidden:true, search:true, editrules:{searchhidden:true}
//				editoptions:{multiple:true, size:4... } 
				key: true
			},

Comment envoyer un champ non éditable lors de la soumission du formulaire ?

  • Si on active hidden:true et editable:true, le champs est correctement envoyé, mais il n'est plus visible sur votre grille.
  • Si on active editable:false, il n'est pas envoyé à la validation du formulaire
  • On peut (seulement dans le cas d'une clé primaire sur un seul champs et pas de type string (problème avec les quotes ' ") utiliser l'attribut key:true, dans ce cas ci le champs sera visible, envoyé, mais pas éditable. Mais attention, son nom sera renommé en id à la place de votre table_id déclaré dans le colModel.
  • Au final, si l'on souhaite liste le champ dans la table, l'envoyer depuis le formulaire, et qu'il ne soit pas éditable il faut le mettre en lecture seule : editoptions:{readonly:true} (set column width and hide primary key when edit)

Pour les index utilisant des clefs primaires composées, il faut composer sa clé primaire avant l'envoi vers la grille, et sur le serveur, décomposer cette clef primaire :

Voir : comment afficher des champs selon l'édition ou la création

Use beforeShowForm for edit and in edit show it in add hide it.

Suppose you have a column with name defined in colModel as myname, the for edit

beforeShowForm : function(formid) {
   $("#tr_myname",formid).show();
}

for add

beforeShowForm : function(formid) {
   $("#tr_myname",formid).hide();
}

editable boolean Defines if the field is editable. This option is used in inline and form modules. false editoptions array Array of allowed options (attributes) for edittype option empty array editrules array editrules: {edithidden:true(false), required:true(false), number:true(false), minValue:val, maxValue:val, email:true(false), date:true(false)} empty array

 edithidden: if true, fields hidden in the grid are included as editable in form editing when add or edit methods are called.  searchhidden: if true, fields hidden in the grid are included in the search form.  required: if true the value will be checked and, if it is empty, an error message will be displayed.  number: if true the value will be checked to be sure it is a number and, if it is not, an error message will be displayed.  i nteger: if true the value will be checked to be sure it is an integer and, if it is not, an error message will be displayed.  minValue: if set to a valid number, the value will be checked and if it is less than the minValue, an error message will be displayed.  maxValue: the same as minValue but the value will be checked to be sure it is not greater than the maxValue.  email: if true, the value will be checked to ensure it conforms to a valid e-mail format (not that the email address exists) and, if it does not, an error message will be displayed.  date: if set to true, the format of the field is governed by the setting of the datefmt

parameter



When a field is not required, the validation rules do not fire and so do not raise an alert for missing data. For example, colModel: [ ... {...editrules:{required:false, number:true..}...} ... ] In this case, if no data is provided by the user (it is left blank) the alert message does not appear - i.e. this is considered to be valid input.

edittype string Defines the edit type for inline and form editing Possible values: text, textarea, select, checkbox, password See also Inline editing and form editing text

Formatter jqGrid

Pour afficher un lien dans votre jqGrid, il faut utiliser un formatter (jqGrid / js / jquery.fmatter.js) :

colNames:['Id','Date'], 
		colModel:[ 
			{name:'reception_id', index:'reception_id', width:15, align:"center",
				formatter:'showlink',	// link / showlink
				formatoptions:{target:"_new", baseLinkUrl:"baseLinkUrl", showAction: 'showAction', idName: "idName", addParam: '&param1=val1&param2=val2'}	// {target:"_new", baseLinkUrl:'someurl.php', addParam: '&action=edit'}
			}, //  jsonmap:'reception_id', hidden:true
			{name:'la_date', index:'la_date', width:30, align:"center", 
			    formatter:"date",
//			    formatoptions:{srcformat:"Y-m-d", newformat:"m/d/Y"}, 	// srcformat:"Y-m-d H:i:s"	Ce fait automatiquement en FR puisque l'on a charger le .fr.js
				searchoptions:{dataInit:datePick, sopt:['eq','ne'], attr:{title:'Select Date'}}
			},
  • link : http://mon.serveur.com/123
  • showlink : http://mon.serveur.com/baseLinkUrlshowAction?idName=123&param1=val1&param2=val2
    • Les options par défaut du showlink selon : grid.locale-fr.js
      • baseLinkUrl:""
      • showAction:""
      • target:""
      • idName:"id"

Pour comprendre, voyez les extraits de code de jquery.fmatter.js

$.fn.fmatter.link = function(cellval, opts) {
		var op = {target:opts.target };
		var target = "";
		if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) {
			op = $.extend({},op,opts.colModel.formatoptions);
		}
		if(op.target) {target = 'target=' + op.target;}
		if(!$.fmatter.isEmpty(cellval)) {
			return "<a "+target+" href=\"" + cellval + "\">" + cellval + "</a>";
		}else {
			return $.fn.fmatter.defaultFormat(cellval,opts);
		}
	};
	$.fn.fmatter.showlink = function(cellval, opts) {
		var op = {baseLinkUrl: opts.baseLinkUrl,showAction:opts.showAction, addParam: opts.addParam || "", target: opts.target, idName: opts.idName },
		target = "", idUrl;
		if(!$.fmatter.isUndefined(opts.colModel.formatoptions)) {
			op = $.extend({},op,opts.colModel.formatoptions);
		}
		if(op.target) {target = 'target=' + op.target;}
		idUrl = op.baseLinkUrl+op.showAction + '?'+ op.idName+'='+opts.rowId+op.addParam;
		if($.fmatter.isString(cellval) || $.fmatter.isNumber(cellval)) {	//add this one even if its blank string
			return "<a "+target+" href=\"" + idUrl + "\">" + cellval + "</a>";
		}else {
			return $.fn.fmatter.defaultFormat(cellval,opts);
		}
	};

Colorier une cellule de la grille

// Vous pouvez colorier une cellule jqGrid avec ceci :
// row_id (l'id de ligne selon key ou non : 1-x)
// col_id (l'id de la colonne : 0-x
//					jQuery("#liste").setCell(row_id,'col_name','',{'background-color':'green'});
					jQuery("#liste").setCell(row_id,col_id,'',{'background-color':'green'});

Dans un grid

afterInsertRow:function(row_id,rData) {
   if(rData['share'] == 'yes') {
      jQuery("#mylinks_grid_table").setCell(row_id,'share','',{background:'red'},{title:'This link has been shared'});
   }
}

new_id afterSubmit add method : Comment récupérer le nouvel ID du serveur ?

afterSubmit : fires after response has been received from server. Typically used to display status from server (e.g., the data is successfully saved or the save cancelled for server-side editing reasons). Receives as parameters the data returned from the request and an array of the posted values of type id=value1,value2. When used this event should return array with the following items [success, message, new_id] where

  • success is a boolean value if true the process continues, if false a error message appear and all other processing is stopped. (message is ignored if success is true).
  • new_id can be used to set the new row id in the grid when we are in add mode.
afterSubmit : function(response, postdata)
 {
 // vos traitements
 return [success,message,new_id]
 }

jqGrid DND Drag and Drop

Drag and Drop rows between grids

Malheureusement, la sélection de multiples lignes à déplacer n'est pas implémentée...

Help

Feature Request