jQuery – Hướng dẫn tổng quan về jqGrid Plugin

Bài viết này tổng hợp lại và cung cấp cho bạn một cái nhìn tổng quát về các chức năng cũng như cách sử dụng component này. Đây là một jQuery Grid Plugin được sử dụng khá phổ biến để hiển thị và quản lý dữ liệu dưới dạng bảng. Chức năng của nó rất nhiều, tôi chỉ giới thiệu những đặc điểm chính và cách sử dụng nó bên client script.

Note: Bài viết này không nhằm mục đích giới thiệu cho bạn cách dùng jqGrid từ A-Z mà chỉ có thể coi là một bài giới thiệu sơ lược hoặc tham khảo nhanh. Để tìm hiểu. Vì vậy nếu bạn chưa từng làm việc với jqGrid, hãy đọc bài hướng dẫn tại link bên dưới trước khi bắt đầu:

My First Grid: http://www.trirand.com/jqgridwiki/doku.php?id=wiki:first_grid

Giới thiệu

– An Ajax-enabled JavaScript control.
– A plugin for jQuery Library.
– Provides solutions for representing and manipulating tabular data on the web.
– Can be integrated with any server-side technology, including PHP, ASP, Java Servlets, JSP, ColdFusion, and Perl.

jqGrid có thể xử lý được nhiều loại nguồn dữ liệu khác nhau như :
– xml, xmlstring
– json, jsonp, jsonstring
– array
– function (…)

Các phần trên giao diện của jqGrid:


(Source: http://www.trirand.com/jqgridwiki)

Các chức năng cơ bản

– CSS based themes (jqGrid is compatible with UI Theming).
– Paging.
– Resizable Columns.
– Sorting & various data types.
– Auto loading data when scrolling.
– Cross browser. Supports for IE 6.0+, FireFox 2.0+, Safari 3.0+, Opera 9.2+ and Google Chrome.
– Multilanguage support (more than 20 languages).
– Support for XML, JSON and arrays as data sources.
– SubGrids.

Cấu hình toàn cục

Cấu hình mặc định của jqGrid được lưu trong jQuery.jgrid.defaults, vì vậy bạn có thể thay đổi nó để ảnh hưởng cho toàn bộ grid được tạo ra. Ở đây tôi dùng phương thức jQuery.extend() để thực hiện gộp hai đối tượng config lại.

$.extend(jQuery.jgrid.defaults, {
		jsonReader : {
			  id: "0",
			  repeatitems: false
		},
		mtype: 'POST',
		sortname: '',
		toppager:false,
		rowNum: 50,
		viewrecords: true,
		loadtext: "Loading...",
		height: "550px",
		rowList: [50,100,500,1000],
		gridComplete: function(grid){
			 // do something, such as resizing grid...
		}
});

Lấy dữ liệu kiểu JSON

Đôi với mỗi kiểu dữ liệu (xml, json, local), bạn cần có một đối tượng reader tương ứng để giúp jqGrid hiểu được cấu trúc của dữ liệu. Ví dụ với kiểu dữ liệu JSON, jqGrid định nghĩa sẵn một jsonReader như sau:

 jQuery("#gridid").jqGrid({
...
   jsonReader : {
     root: "rows", 				// points to the array that contains data
     page: "page", 				// current page
     total: "total", 			// total pages
     records: "records", 		// total records
     repeatitems: true, 		// the data in the row is repeatable
     cell: "cell", 	 			// name of array which contains data for the row.
     id: "id",  				// descibes the unique id for the row
     userdata: "userdata", 		// custom data returned from the request
	 ...
   },
...
});

Đối tượng reader trên có thể phân tích được dữ liệu JSON trả về từ server sau:

{
  "total": "xxx",
  "page": "yyy",
  "records": "zzz",
  "rows" : [
    {"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "cell":["cell21", "cell22", "cell23"]},
      ...
  ]
}

Giải thích:

Tag Description
total total pages for the query
page current page of the query
records total number of records for the query
rows an array that contains the actual data
id the unique id of the row
cell an array that contains the data for a row

Tạo Grid

Đoạn code minh họa việc tạo một jqGrid trên một table có id là list và thẻ div#pager làm navigator để chứa các thành phần phân trang và các nút nhấn thao tác với dữ liệu.

...
<table id="list"><tr><td/></tr></table>
<div id="pager"></div>
...
<script type='text/javascript'>
	$("#list").jqGrid({
	jsonReader : {
		id: "0",
		repeatitems: false
	},
	url: 'example.php',
	datatype: 'json',
	mtype: 'GET',
	colNames: ['Id','Name','Regionid','Region','Description','Displayorder', 'Enabled'],
	colModel :[
		  {name:'countryid', index:'countryid', width:50,align: 'center',key: true},
		  {name:'countryname', index:'countryname',},
		  {name:'regionid', index:'regionid', hidden: true},
		  {name:'regionname', index:'regionname'},
		  {name:'description', index:'description'},
		  {name:'displayorder', index:'displayorder',align: 'center'},
		  {name:'isenabled', index:'isenabled', width:80,align: 'center',formatter: "checkbox"}
	],
	pager: '#pager',
	viewrecords: true,
	caption: "Countries Table"
 });
 </script>
 

Navigating

Để kích hoạt các built-in button (add, edit, del, view, search) trên thanh navigator của jqGrid, cần gọi phương thức navGrid() cùng với các tùy chọn sau khi đã tạo grid:

// config the built-in buttons for the pager
$grid.jqGrid("navGrid",'#pager1',
	{
	search: false, view:true, edit: true, add: true, del: true,
	},
	// edit options
	options,
	// add options
	options,
	// del_options, search_options, view_options
);

Ta cũng có thể thêm các button khác vào bằng cách dùng navButtonAdd():

// add a custom button to navigator
$grid.jqGrid("navButtonAdd", "#pager1",{
	caption:"Click Me",
	buttonicon:"none",
	onClickButton: function(){
		alert("Hello! I'm a custom button.");
	},
	position:"last"
});

Kết quả:

Searching

Mặc định jqGrid cung cấp sẵn chức năng Single Search khi được kích hoạt button Search cho navigator. Ta có thể thêm tùy chọn {multipleSearch:true} cho tham số search_options (xem phần trên) để jqGrid chuyển sang chức năng Advanced Search. Chức năng này cho phép tìm kiếm với nhiều điều kiện phức tạp hơn.

Để search dựa vào toolbar, ta gọi phương thức filterToolbar():

$grid.jqGrid('filterToolbar',options);

Giao diện Inline và Advanced Searching:

Editing

jqGrid cung cấp ba cách thức để chỉnh sửa dữ liệu là Cell, Inline và Form. Cách sửa bằng Form đã được tích hợp vào trong button Edit của navigator.
Trước tiên, khi tạo grid, ta xác định các cột được phép sửa dữ liệu trong colModel với hai thuộc tính editable và edittype:

colModel :[
		      {name:'countryid', index:'countryid', align: 'center',key: true},
		      {name:'countryname', index:'countryname', width:150,editable:true, edittype:'text'},
		      {name:'regionid', index:'regionid', hidden: true,editable:true, edittype:'text'},
		      {name:'regionname', index:'regionname', width:150,editable:true, edittype:'text'},
		      {name:'description', index:'description', width:150,editable:true, edittype:'text'},
		      {name:'displayorder', index:'displayorder',align: 'center',editable:true, edittype:'text'},
		      {name:'isenabled', index:'isenabled', width:80,align: 'center',formatter: "checkbox",editable:true, edittype:'checkbox'}
	    ]

Để kích hoạt tính năng Cell Editing (sửa một ô trong bảng dữ liệu), ta thêm hai tùy chọn cellEdit và cellurl khi tạo grid:

// Creating grid with cell editing support
$grid.jqGrid({
	// ...
	cellEdit : true,
	cellurl : '/url/to/handling/the/changed/cell/value'
});

Đối với tính năng Inline Editing (sửa nguyên một dòng dữ liệu), ta sẽ xử lý sự kiện onSelectRow và gọi phương thức editRow() trong đó:

// Handle the onSelectRow event when creating grid
$grid.jqGrid({
	// ...
	onSelectRow: function(id){
	if(id && id!==lastSel){
		$grid.restoreRow(lastSel); // you can call saveRow() instead
		lastSel=id;
	}
	$grid.editRow(id, true);
	}});

Giao diện Form Editing:

Grouping

Gom nhóm dữ liệu:
– Dữ liệu trong bảng sẽ được gom thành từng phần dựa vào các cột được chỉ định. Khi tạo grid, ta cung cấp các tùy chọn sau để gom dữ liệu theo cột regionname và chiều sắp xếp là tăng dần (asc). Lưu ý groupField và groupOrder là kiểu mảng nên bạn có thể truyền vào nhiều cột khác nhau.

$grid.jqGrid({
	// ...
	grouping: true,
	groupingView : {
	groupField : ['regionname'],
	groupOrder :  ['asc']
}});

Ngoài khả năng gom nhóm dữ liệu, jqGrid có thể gom các tiêu đề cột với nhau (Header Grouping) bằng phương thức setGroupHeaders():

$grid.jqGrid('setGroupHeaders', {
	useColSpanStyle: true,
	groupHeaders:[
			{startColumnName: 'countryid', numberOfColumns: 2,
				titleText: '<em>Info</em>'},
			{startColumnName: 'description', numberOfColumns: 2,
				 			titleText: 'Config'}
	]
});

Kết quả:

Formatter

Để định dạng hiển thị cho từng loại dữ liệu, jqGrid cung cấp các Predefined Formatter như number, date, link, checkbox,… Ngoài ra, ta có thể tự tạo các custom formatter để định dạng cho các cột dữ liệu đặc biệt.
Ví dụ tôi tạo một custom formatter với tên myformatter và gán cho thuộc tính formatter cho cột tương ứng trong mảng colModel.

$grid.jqGrid({
	// ...
    colModel :[
	      {name:'countryname', index:'countryname', formatter: myformatter },
	    // ...
    ]
});

myfomatter thực chất là một function với ba tham số đặc biệt:

function myformatter ( cellvalue, options, rowObject )
{
	return rowObject.countryid +
		" - <span class="highlight">" + cellvalue + "</span>";
}

– cellvalue – the value to be formatted
– options – an object containing the following element
options : { rowId: rid, colModel: cm}
– rowObject – a row data represented in the format determined from datatype option.
Kết quả:

Tham khảo

YinYangIt’s Blog

4 bình luận về “jQuery – Hướng dẫn tổng quan về jqGrid Plugin

    • Đúng vậy, jQuery UI là một thư viện rất phổ biến và là ưu tiên đầu trong các dự án của mình. Tuy nhiên jQuery UI không bao gồm một client grid. Grid là một control khá lớn và phức tạp nên được tách riêng ra các dự án khác. jqGrid khá nổi tiếng trong rất nhiều các thư viện grid bằng javascript hiện nay. Đây cũng chỉ là một bài giới thiệu tổng quan do mình có kinh nghiệm làm việc với nó, ko phải là đề xuất tốt nhất mà mình đưa ra :).

Đã đóng bình luận.