上一篇文章,在Grid中加入了多选/全选功能,实际运用中,我们可能需要动态修改Grid中的数据,也就是要实现EditGrid功能。本文介绍如何实现Extjs4 EditGrid功能。先发几张效果图。看图说话,更有说服力哦。
HTML代码:
- <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <htmlxmlns="http://www.w3.org/1999/xhtml">
- <head>
- <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
- <title>ExtJS4EditGrid(可编辑的Grid)-MHZG.NET</title>
- <linkrel="stylesheet"type="text/css"href="../../resources/css/ext-all.css"/>
- <linkrel="stylesheet"type="text/css"href="../../examples/ux/css/CheckHeader.css"/>
- <styletype="text/css">
- #search-resultsa{
- color:#385F95;
- font:bold11pxtahoma,arial,helvetica,sans-serif;
- text-decoration:none;
- }
- .add{
- background-image:url(../../examples/shared/icons/fam/cog.gif)!important;
- }
- #search-resultsa:hover{
- text-decoration:underline;
- }
- #search-resultsp{
- margin:3px!important;
- }
- .search-item{
- font:normal11pxtahoma,arial,helvetica,sans-serif;
- padding:3px10px3px10px;
- border:1pxsolid#fff;
- border-bottom:1pxsolid#eeeeee;
- white-space:normal;
- color:#555;
- }
- .search-itemh3{
- display:block;
- font:inherit;
- font-weight:bold;
- color:#222;
- }
-
- .search-itemh3span{
- float:right;
- font-weight:normal;
- margin:005px5px;
- width:100px;
- display:block;
- clear:none;
- }
- .x-form-clear-trigger{
- background-image:url(../../resources/themes/images/default/form/clear-trigger.gif);
- }
- .x-form-search-trigger{
- background-image:url(../../resources/themes/images/default/form/search-trigger.gif);
- }
- </style>
- <scripttype="text/javascript"src="../../bootstrap.js"></script>
- <scripttype="text/javascript"src="../../locale/ext-lang-zh_CN.js"></script>
- <scripttype="text/javascript"src="editgrid.js"></script>
- </head>
-
- <body>
- <divid="demo"></div>
- </body>
- </html>
editgrid.js:
- Ext.Loader.setConfig({enabled:true});
- Ext.Loader.setPath('Ext.ux','../../examples/ux');
- Ext.require([
- 'Ext.grid.*',
- 'Ext.toolbar.Paging',
- 'Ext.util.*',
- 'Ext.data.*',
- 'Ext.state.*',
- 'Ext.form.*',
- 'Ext.ux.form.SearchField',
- 'Ext.selection.CellModel',
- 'Ext.ux.CheckColumn',
- 'Ext.selection.CheckboxModel'
- ]);
-
- Ext.onReady(function(){
- varisEdit=false;
- functionformatDate(value){
- returnvalue?Ext.Date.dateFormat(value,'Y-m-d'):'';
- }
- Ext.define('MyData',{
- extend:'Ext.data.Model',
- fields:[
- {name:'id'},
- {name:'title',type:'string'},
- {name:'author'},
- {name:'hits',type:'int'},
- {name:'addtime',type:'date',dataFormat:'Y-m-d'},
- {name:'checked',type:'bool'}
- ]
- });
- //创建数据源
- varstore=Ext.create('Ext.data.Store',{
- //分页大小
- pageSize:50,
- model:'MyData',
- //是否在服务端排序
- remoteSort:true,
- autoDestroy:true,
- proxy:{
- //异步获取数据,这里的URL可以改为任何动态页面,只要返回JSON数据即可
- type:'ajax',
- url:'editgrid.asp',
- reader:{
- root:'items',
- totalProperty:'total'
- },
- simpleSortMode:true
- },
- sorters:[{
- //排序字段。
- property:'hits',
- //排序类型,默认为ASC
- direction:'DESC'
- }]
- });
- //下拉框数据,测试数据。
- varcbstore=Ext.create('Ext.data.Store',{
- fields:['id','name'],
- data:[
- {"id":"1","name":"佚名"},
- {"id":"2","name":"管理员"},
- {"id":"3","name":"编辑"},
- {"id":"4","name":"总编辑"},
- {"id":"5","name":"测试员"}
- ]
- });
-
- //创建多选
- varselModel=Ext.create('Ext.selection.CheckboxModel');
- varcellEditing=Ext.create('Ext.grid.plugin.CellEditing',{
- clicksToEdit:1
- });
- //创建Grid
- vargrid=Ext.create('Ext.grid.Panel',{
- store:store,
- selModel:selModel,
- columnLines:true,
- columns:[{
- id:"title",
- header:"标题",
- width:110,
- dataIndex:'title',
- sortable:true,
- field:{
- allowBlank:false
- }
- },{
- header:"作者",
- width:120,
- dataIndex:'author',
- id:'gc',
- sortable:false,
- field:{
- xtype:'combobox',
- id:'authors',
- typeAhead:true,
- triggerAction:'all',
- queryMode:'local',
- selectOnTab:true,
- store:cbstore,
- lazyRender:true,
- displayField:'name',
- valueField:'id',
- listClass:'x-combo-list-small',
- listeners:{
- select:function(combo,record,index){
- isEdit=true;
- }
- }
- },
- renderer:rendererData
- },{
- header:"点击数",
- width:80,
- dataIndex:'hits',
- sortable:true,
- field:{
- xtype:'numberfield',
- allowBlank:false,
- minValue:0,
- maxValue:100000
- }
- },{
- header:"添加时间",
- width:100,
- dataIndex:'addtime',
- sortable:true,
- renderer:formatDate,
- field:{
- xtype:'datefield',
- format:'y-m-d',
- minValue:'01/01/06'
- }
- },{
- xtype:'checkcolumn',
- header:'审核',
- dataIndex:'checked',
- width:55
- }],
- height:400,
- width:520,
- x:20,
- y:40,
- title:'ExtJS4EditGrid(可编辑的Grid)',
- disableSelection:false,//值为TRUE,表示禁止选择
- frame:true,
- selType:'cellmodel',
- loadMask:true,
- renderTo:'demo',
- viewConfig:{
- id:'gv',
- trackOver:false,
- stripeRows:false
- },
- dockedItems:[{
- dock:'top',
- xtype:'toolbar',
- items:[{
- itemId:'Button',
- text:'显示所选',
- tooltip:'Addanewrow',
- iconCls:'add',
- handler:function(){
- varrecord=grid.getSelectionModel().getSelection();
- if(record.length==0){
- Ext.MessageBox.show({
- title:"提示",
- msg:"请先选择您要操作的行!",
- icon:Ext.MessageBox.INFO,
- buttons:Ext.Msg.OK
- })
- return;
- }else{
- varids="";
- for(vari=0;i<record.length;i++){
- ids+=record[i].get("id")
- if(i<record.length-1){
- ids=ids+",";
- }
- }
- Ext.MessageBox.show({
- title:"所选ID列表",
- msg:ids
- //icon:Ext.MessageBox.INFO
- })
- }
- }
- },'-',{
- width:300,
- fieldLabel:'搜索',
- labelWidth:50,
- xtype:'searchfield',
- store:store
- }]
- },{
- dock:'bottom',
- xtype:'pagingtoolbar',
- store:store,
- pageSize:25,
- displayInfo:true,
- displayMsg:'显示{0}-{1}条,共计{2}条',
- emptyMsg:'没有数据'
- }],
- plugins:[cellEditing]
- })
- store.loadPage(1);
- grid.on('edit',onEdit,this);
- functiononEdit(){
- varrecord=grid.getSelectionModel().getSelection()[0];
- //这里进行异步操作,关于Extjs的异步操作这里不做演示,仅列出所有值。
- vartitle=record.get('title');
- varauthor=record.get('author');//注意,这里得到的是id值,而不是name值,如果没有修改作者,那么得到的值是默认显示的字符串,这个需要在服务端进行判断并处理。
- varclk=record.get('hits');
- varaddtime=Ext.Date.dateFormat(record.get('addtime'),'Y-m-d');
- varchecked=record.get('checked');
- Ext.MessageBox.show({
- title:"修改的数据为",
- msg:title+"\r\n"+author+"\r\n"+clk+"\r\n"+addtime+"\r\n"+checked,
- icon:Ext.MessageBox.INFO,
- buttons:Ext.Msg.OK
- })
- }
- functionrendererData(value,metadata,record){
- if(isEdit){
- varindex=cbstore.find(Ext.getCmp('authors').valueField,value);
- varrecord=cbstore.getAt(index);
- returnrecord.data.name;
- }else{
- returnvalue;
- }
- }
- })
editgrid.asp:时间关系,只简单做了些测试数据。
- <%
- Response.ContentType="text/html"
- Response.Charset="UTF-8"
- %>
- <%
- '返回JSON数据,自定义一些测试数据。。
- '这里的参数与EXT3.x相同,区别在于排序字段和排序方式使用了新的属性。
- '由于这里是测试数据,接收的参数只用到了start,limit。sorts和dir在实际操作过程中,将之加入SQL的ORDERBY里即可。
- start=Request("start")
- limit=Request("limit")
- '查询时获取的参数。
- query=Request("query")
- Ifstart=""Then
- start=0
- EndIf
- Iflimit=""Then
- limit=50
- EndIf
- sorts=Replace(Trim(Request.Form("sort")),"'","")
- dir=Replace(Trim(Request.Form("dir")),"'","")
-
- '测试数据,这里直接输出结果,实际应用中,应该把查询条件放到SQL语句中。
- Ifquery="newstitle"Then
- Echo("{")
- Echo("""total"":")
- Echo("""1")
- Echo(""",""items"":[")
- Echo("{")
- Echo("""title"":""newstitle""")
- Echo(",")
- Echo("""author"":""author""")
- Echo(",")
- Echo("""hits"":""100""")
- Echo(",")
- Echo("""addtime"":"""&Now()&"""")
- Echo("}")
- Echo("]}")
- Else
- Dimcounts:counts=20
- '注意,这里的counts相当于Rs.RecordCount,也就是记录总数。
-
- DimLs:Ls=Cint(start)+Cint(limit)
- IfLs>=countsThen
- Ls=counts
- EndIf
-
- Echo("{")
- Echo("""total"":")
- Echo(""""&counts&""",")
- Echo("""items"":[")
- Fori=start+1ToLs
- Echo("{")
- Echo("""id"":"""&i&"""")
- Echo(",")
- Echo("""title"":""newstitle"&i&"""")
- Echo(",")
- Echo("""author"":""author"&i&"""")
- Echo(",")
- Echo("""hits"":"""&i&"""")
- Echo(",")
- Echo("""addtime"":"""&Now()&"""")
- Echo(",")
- IfiMod4=0Then
- Echo("""checked"":""true""")
- Else
- Echo("""checked"":""false""")
- EndIf
- Echo("}")
- Ifi<LsThen
- Echo(",")
- EndIf
- Next
-
- Echo("]}")
- EndIf
- FunctionEcho(str)
- Response.Write(str)
- EndFunction
- %>
由于4.x有了重大更新,所以很多在3.x中的东西在4.x里并不好使,直接导致了本文迟迟没有发表,原因就出在了更新下拉框后,Grid中显示的是ID号而不是name值。一番查看API及研究,终于发现问题所在,3.x中renderer combobox在4.x并不好用,最后重新读了一遍自己写的代码,才有所顿悟。希望文章能起到一个抛砖引玉的作用,大家一起进步。