Simple Example of How To Get Started With Jqgrid On Web2py

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 6
At a glance
Powered by AI
The key steps are to include jqGrid files, define a model and table, populate with dummy data, and configure the grid to pull and display data.

You need to download jqGrid, include the necessary files, define the grid configuration and URL to fetch data from.

You can use the populate function from gluon.contrib.populate to insert dummy records into the database tables.

Setting Up

Download jqGrid from here, extract it to your static folder and include it using
response.files in your controller. It requires jQueryUI which we can link direc
tly from google.
Select
def index():
response.files.append("http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/j
query-ui.min.js")
response.files.append(URL(r=request,c='static/jqueryui/css/ui-darkness',f='j
query-ui-1.7.2.custom.css'))
response.files.append(URL(r=request,c='static/jquery.jqGrid/src/i18n',f='gri
d.locale-en.js'))
response.files.append(URL(r=request,c='static/jquery.jqGrid/js',f='jquery.jq
Grid.min.js'))
response.files.append(URL(r=request,c='static/jquery.jqGrid/css',f='ui.jqgri
d.css'))
return dict()
Let's build a test model and fill it with dummy data
Select
from gluon.contrib.populate import populate
db.define_table('category',
Field('name'))
db.define_table('things',
Field('name'),
Field('quantity','integer'),
Field('owner'),
Field('price','double'),
Field('category',db.category))
if db(db.things.id>0).count() == 0:
populate(db.category,10)
populate(db.things,50)
Making it Work
Our test grid will live in the index view. Let's set it up to pull json data fro
m an action called get_rows.
Select
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url:'{{=URL(r=request,f='call',args=['json','get_rows'])}}',
data: "{}",
datatype: 'json',
mtype: 'GET',
contentType: "application/json; charset=utf-8",
complete: function(jsondata, stat) {
if (stat == "success") {
var thegrid = jQuery("#list")[0];
thegrid.addJSONData(JSON.parse(jsondata.responseText).d);
}
},
colNames:['ID','Name','Category', 'Price','Owner'],
colModel :[
{name:'id',index:'id', width:55},
{name:'name', index:'name'},
{name:'category', index:'category'},
{name:'price', index:'price'},
{name:'owner', index:'owner'}
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'name',
sortorder: 'desc',
viewrecords: true,
caption: 'Test Grid'
});
});
</script>
<table id="list"></table>
<div id="pager"></div>
Make sure you are exposing the service. This should be in your default controlle
r.
Select
def call():
"""
exposes services. for example:
http://..../[app]/default/call/jsonrpc
decorate with @services.jsonrpc the functions to expose
supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
"""
session.forget()
return service()
Now let's setup an action to serve json to the grid using our service. jqGrid re
quires a specific format for the json. Read the jqGrid docs for details.
Select
@service.json
def get_rows():
db.things.category.represent = lambda v: v.name
fields = ['id','name','category','price','owner']
rows = []
page = int(request.vars.page)
pagesize = int(request.vars.rows)
limitby = (page * pagesize - pagesize,page * pagesize)
orderby = db.things[request.vars.sidx]
if request.vars.sord == 'desc': orderby = ~orderby
for r in db(db.things.id>0).select(limitby=limitby,orderby=orderby):
vals = []
for f in fields:
rep = db.things[f].represent
if rep:
vals.append(rep(r[f]))
else:
vals.append(r[f])
rows.append(dict(id=r.id,cell=vals))
total = db(db.things.id>0).count()
pages = int(total/pagesize)
#if total % pagesize == 0: pages -= 1
data = dict(total=pages,page=page,rows=rows)
return data
alt text
jqGrid is a comprehensive data grid with many options and a robust api. This is
just a simple example of how to get started.
Select All
Overall:
(1 vote)
Log in to rate, save, subscribe and view history
Comments (3):
Subscribe to receive replies and updates
tomyblack 2010-05-06
Hi,
How can I to write data to the server ?
mr.freeze 2010-05-06
I would take a look at the documentation about the different kinds of editing yo
u can do. I believe all methods for editing have callbacks to the server.
tomyblack 2010-05-09
Hi again,
I can now edit but add and delete button doesn't work. What am I doing wrong or
what's missing ?
------------
Controller:
------------
Select

@service.json
def getjson():
page=int((request.vars.page))
limit=int((request.vars.rows))
rcount=db(db.things.id>0).count()
total_pages=int(ceil(rcount*1.0/limit))
start = limit*page-limit
records = db(db.things.id>0).select(limitby=(start,start+limit))
cellist=[]
mylist={}
mylist['total']=str(total_pages)
mylist['page']=str(page)
mylist['records']=str(rcount)
for row in records:
temp={}
temp['id']=str(row.id)
temp['cell']=[row.id,row.name,row.category,row.price,row.owner]
cellist=cellist+[temp]
mylist['rows']=cellist
return(mylist)

@service.json
def setjson():
value=request.vars
id=value['id']
name=value['name']
category=value['category']
price=value['price']
owner=value['owner']
db(db.things.id==id).update(name=name, category=category, price=price, owner
=owner)

------------------------
View.html
------------------------
Select

{{extend 'layout.html'}}
<script>
jQuery("#list").jqGrid('navGrid',selector,options,pEdit,pAdd,pDel,pSearch );
</script>
<script>
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
url:'{{=URL(r=request,f='call',args=['json','getjson'])}}',
data: "{}",
datatype: 'json',
mtype: 'GET',
contentType: "application/json; charset=utf-8",
complete: function(jsondata, stat) {
if (stat == "success") {
var thegrid = jQuery("#list")[0];
thegrid.addJSONData(JSON.parse(jsondata.responseText).d);
}
},

colNames:['ID','Name','Category', 'Price','Owner'],
colModel :[
{name:'id',index:'id', width:55,sortable:false, editable:true, editoptions
:{readonly:true,size:10}},
{name:'name', index:'name',width:200,editable:true},
{name:'category', index:'category',width:200,editable:true},
{name:'price', index:'price',width:200,editable:true},
{name:'owner', index:'owner',width:200,editable:true},
],
jsonReader : {
repeatitems:true
},
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'name',
sortorder: 'desc',
viewrecords: true,
caption: 'Test Grid',
editurl:'{{=URL(r=request,f='call',args=['json','setjson'])}}'}).navGrid('#p
ager');

});
jQuery("#list").jqGrid('navGrid','#pager',
{view:true}, //options
{height:290,reloadAfterSubmit:false, jqModal:false, closeOnEscape:true, bottomin
fo:"Fields marked with (*) are required"}, // edit options
{height:290,reloadAfterSubmit:false,jqModal:false, closeOnEscape:true,bottominfo
:"Fields marked with (*) are required", closeAfterAdd: true}, // add options
{reloadAfterSubmit:false,jqModal:false, closeOnEscape:true}, // del options
{closeOnEscape:true}, // search options
{height:250,jqModal:false,closeOnEscape:true} // view options
);
<table> </table>
<div> </div>

You might also like