ExtJS4学习笔记(十二)---ExtJS4 EditGrid(可编辑的Grid)

上一篇文章,在Grid中加入了多选/全选功能,实际运用中,我们可能需要动态修改Grid中的数据,也就是要实现EditGrid功能。本文介绍如何实现Extjs4 EditGrid功能。先发几张效果图。看图说话,更有说服力哦。






HTML代码:

  1. <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <htmlxmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
  5. <title>ExtJS4EditGrid(可编辑的Grid)-MHZG.NET</title>
  6. <linkrel="stylesheet"type="text/css"href="../../resources/css/ext-all.css"/>
  7. <linkrel="stylesheet"type="text/css"href="../../examples/ux/css/CheckHeader.css"/>
  8. <styletype="text/css">
  9. #search-resultsa{
  10. color:#385F95;
  11. font:bold11pxtahoma,arial,helvetica,sans-serif;
  12. text-decoration:none;
  13. }
  14. .add{
  15. background-image:url(../../examples/shared/icons/fam/cog.gif)!important;
  16. }
  17. #search-resultsa:hover{
  18. text-decoration:underline;
  19. }
  20. #search-resultsp{
  21. margin:3px!important;
  22. }
  23. .search-item{
  24. font:normal11pxtahoma,arial,helvetica,sans-serif;
  25. padding:3px10px3px10px;
  26. border:1pxsolid#fff;
  27. border-bottom:1pxsolid#eeeeee;
  28. white-space:normal;
  29. color:#555;
  30. }
  31. .search-itemh3{
  32. display:block;
  33. font:inherit;
  34. font-weight:bold;
  35. color:#222;
  36. }

  37. .search-itemh3span{
  38. float:right;
  39. font-weight:normal;
  40. margin:005px5px;
  41. width:100px;
  42. display:block;
  43. clear:none;
  44. }
  45. .x-form-clear-trigger{
  46. background-image:url(../../resources/themes/images/default/form/clear-trigger.gif);
  47. }
  48. .x-form-search-trigger{
  49. background-image:url(../../resources/themes/images/default/form/search-trigger.gif);
  50. }
  51. </style>
  52. <scripttype="text/javascript"src="../../bootstrap.js"></script>
  53. <scripttype="text/javascript"src="../../locale/ext-lang-zh_CN.js"></script>
  54. <scripttype="text/javascript"src="editgrid.js"></script>
  55. </head>

  56. <body>
  57. <divid="demo"></div>
  58. </body>
  59. </html>

editgrid.js:

  1. Ext.Loader.setConfig({enabled:true});
  2. Ext.Loader.setPath('Ext.ux','../../examples/ux');
  3. Ext.require([
  4. 'Ext.grid.*',
  5. 'Ext.toolbar.Paging',
  6. 'Ext.util.*',
  7. 'Ext.data.*',
  8. 'Ext.state.*',
  9. 'Ext.form.*',
  10. 'Ext.ux.form.SearchField',
  11. 'Ext.selection.CellModel',
  12. 'Ext.ux.CheckColumn',
  13. 'Ext.selection.CheckboxModel'
  14. ]);

  15. Ext.onReady(function(){
  16. varisEdit=false;
  17. functionformatDate(value){
  18. returnvalue?Ext.Date.dateFormat(value,'Y-m-d'):'';
  19. }
  20. Ext.define('MyData',{
  21. extend:'Ext.data.Model',
  22. fields:[
  23. {name:'id'},
  24. {name:'title',type:'string'},
  25. {name:'author'},
  26. {name:'hits',type:'int'},
  27. {name:'addtime',type:'date',dataFormat:'Y-m-d'},
  28. {name:'checked',type:'bool'}
  29. ]
  30. });
  31. //创建数据源
  32. varstore=Ext.create('Ext.data.Store',{
  33. //分页大小
  34. pageSize:50,
  35. model:'MyData',
  36. //是否在服务端排序
  37. remoteSort:true,
  38. autoDestroy:true,
  39. proxy:{
  40. //异步获取数据,这里的URL可以改为任何动态页面,只要返回JSON数据即可
  41. type:'ajax',
  42. url:'editgrid.asp',
  43. reader:{
  44. root:'items',
  45. totalProperty:'total'
  46. },
  47. simpleSortMode:true
  48. },
  49. sorters:[{
  50. //排序字段。
  51. property:'hits',
  52. //排序类型,默认为ASC
  53. direction:'DESC'
  54. }]
  55. });
  56. //下拉框数据,测试数据。
  57. varcbstore=Ext.create('Ext.data.Store',{
  58. fields:['id','name'],
  59. data:[
  60. {"id":"1","name":"佚名"},
  61. {"id":"2","name":"管理员"},
  62. {"id":"3","name":"编辑"},
  63. {"id":"4","name":"总编辑"},
  64. {"id":"5","name":"测试员"}
  65. ]
  66. });

  67. //创建多选
  68. varselModel=Ext.create('Ext.selection.CheckboxModel');
  69. varcellEditing=Ext.create('Ext.grid.plugin.CellEditing',{
  70. clicksToEdit:1
  71. });
  72. //创建Grid
  73. vargrid=Ext.create('Ext.grid.Panel',{
  74. store:store,
  75. selModel:selModel,
  76. columnLines:true,
  77. columns:[{
  78. id:"title",
  79. header:"标题",
  80. width:110,
  81. dataIndex:'title',
  82. sortable:true,
  83. field:{
  84. allowBlank:false
  85. }
  86. },{
  87. header:"作者",
  88. width:120,
  89. dataIndex:'author',
  90. id:'gc',
  91. sortable:false,
  92. field:{
  93. xtype:'combobox',
  94. id:'authors',
  95. typeAhead:true,
  96. triggerAction:'all',
  97. queryMode:'local',
  98. selectOnTab:true,
  99. store:cbstore,
  100. lazyRender:true,
  101. displayField:'name',
  102. valueField:'id',
  103. listClass:'x-combo-list-small',
  104. listeners:{
  105. select:function(combo,record,index){
  106. isEdit=true;
  107. }
  108. }
  109. },
  110. renderer:rendererData
  111. },{
  112. header:"点击数",
  113. width:80,
  114. dataIndex:'hits',
  115. sortable:true,
  116. field:{
  117. xtype:'numberfield',
  118. allowBlank:false,
  119. minValue:0,
  120. maxValue:100000
  121. }
  122. },{
  123. header:"添加时间",
  124. width:100,
  125. dataIndex:'addtime',
  126. sortable:true,
  127. renderer:formatDate,
  128. field:{
  129. xtype:'datefield',
  130. format:'y-m-d',
  131. minValue:'01/01/06'
  132. }
  133. },{
  134. xtype:'checkcolumn',
  135. header:'审核',
  136. dataIndex:'checked',
  137. width:55
  138. }],
  139. height:400,
  140. width:520,
  141. x:20,
  142. y:40,
  143. title:'ExtJS4EditGrid(可编辑的Grid)',
  144. disableSelection:false,//值为TRUE,表示禁止选择
  145. frame:true,
  146. selType:'cellmodel',
  147. loadMask:true,
  148. renderTo:'demo',
  149. viewConfig:{
  150. id:'gv',
  151. trackOver:false,
  152. stripeRows:false
  153. },
  154. dockedItems:[{
  155. dock:'top',
  156. xtype:'toolbar',
  157. items:[{
  158. itemId:'Button',
  159. text:'显示所选',
  160. tooltip:'Addanewrow',
  161. iconCls:'add',
  162. handler:function(){
  163. varrecord=grid.getSelectionModel().getSelection();
  164. if(record.length==0){
  165. Ext.MessageBox.show({
  166. title:"提示",
  167. msg:"请先选择您要操作的行!",
  168. icon:Ext.MessageBox.INFO,
  169. buttons:Ext.Msg.OK
  170. })
  171. return;
  172. }else{
  173. varids="";
  174. for(vari=0;i<record.length;i++){
  175. ids+=record[i].get("id")
  176. if(i<record.length-1){
  177. ids=ids+",";
  178. }
  179. }
  180. Ext.MessageBox.show({
  181. title:"所选ID列表",
  182. msg:ids
  183. //icon:Ext.MessageBox.INFO
  184. })
  185. }
  186. }
  187. },'-',{
  188. width:300,
  189. fieldLabel:'搜索',
  190. labelWidth:50,
  191. xtype:'searchfield',
  192. store:store
  193. }]
  194. },{
  195. dock:'bottom',
  196. xtype:'pagingtoolbar',
  197. store:store,
  198. pageSize:25,
  199. displayInfo:true,
  200. displayMsg:'显示{0}-{1}条,共计{2}条',
  201. emptyMsg:'没有数据'
  202. }],
  203. plugins:[cellEditing]
  204. })
  205. store.loadPage(1);
  206. grid.on('edit',onEdit,this);
  207. functiononEdit(){
  208. varrecord=grid.getSelectionModel().getSelection()[0];
  209. //这里进行异步操作,关于Extjs的异步操作这里不做演示,仅列出所有值。
  210. vartitle=record.get('title');
  211. varauthor=record.get('author');//注意,这里得到的是id值,而不是name值,如果没有修改作者,那么得到的值是默认显示的字符串,这个需要在服务端进行判断并处理。
  212. varclk=record.get('hits');
  213. varaddtime=Ext.Date.dateFormat(record.get('addtime'),'Y-m-d');
  214. varchecked=record.get('checked');
  215. Ext.MessageBox.show({
  216. title:"修改的数据为",
  217. msg:title+"\r\n"+author+"\r\n"+clk+"\r\n"+addtime+"\r\n"+checked,
  218. icon:Ext.MessageBox.INFO,
  219. buttons:Ext.Msg.OK
  220. })
  221. }
  222. functionrendererData(value,metadata,record){
  223. if(isEdit){
  224. varindex=cbstore.find(Ext.getCmp('authors').valueField,value);
  225. varrecord=cbstore.getAt(index);
  226. returnrecord.data.name;
  227. }else{
  228. returnvalue;
  229. }
  230. }
  231. })

editgrid.asp:时间关系,只简单做了些测试数据。

  1. <%
  2. Response.ContentType="text/html"
  3. Response.Charset="UTF-8"
  4. %>
  5. <%
  6. '返回JSON数据,自定义一些测试数据。。
  7. '这里的参数与EXT3.x相同,区别在于排序字段和排序方式使用了新的属性。
  8. '由于这里是测试数据,接收的参数只用到了start,limit。sorts和dir在实际操作过程中,将之加入SQL的ORDERBY里即可。
  9. start=Request("start")
  10. limit=Request("limit")
  11. '查询时获取的参数。
  12. query=Request("query")
  13. Ifstart=""Then
  14. start=0
  15. EndIf
  16. Iflimit=""Then
  17. limit=50
  18. EndIf
  19. sorts=Replace(Trim(Request.Form("sort")),"'","")
  20. dir=Replace(Trim(Request.Form("dir")),"'","")

  21. '测试数据,这里直接输出结果,实际应用中,应该把查询条件放到SQL语句中。
  22. Ifquery="newstitle"Then
  23. Echo("{")
  24. Echo("""total"":")
  25. Echo("""1")
  26. Echo(""",""items"":[")
  27. Echo("{")
  28. Echo("""title"":""newstitle""")
  29. Echo(",")
  30. Echo("""author"":""author""")
  31. Echo(",")
  32. Echo("""hits"":""100""")
  33. Echo(",")
  34. Echo("""addtime"":"""&Now()&"""")
  35. Echo("}")
  36. Echo("]}")
  37. Else
  38. Dimcounts:counts=20
  39. '注意,这里的counts相当于Rs.RecordCount,也就是记录总数。

  40. DimLs:Ls=Cint(start)+Cint(limit)
  41. IfLs>=countsThen
  42. Ls=counts
  43. EndIf

  44. Echo("{")
  45. Echo("""total"":")
  46. Echo(""""&counts&""",")
  47. Echo("""items"":[")
  48. Fori=start+1ToLs
  49. Echo("{")
  50. Echo("""id"":"""&i&"""")
  51. Echo(",")
  52. Echo("""title"":""newstitle"&i&"""")
  53. Echo(",")
  54. Echo("""author"":""author"&i&"""")
  55. Echo(",")
  56. Echo("""hits"":"""&i&"""")
  57. Echo(",")
  58. Echo("""addtime"":"""&Now()&"""")
  59. Echo(",")
  60. IfiMod4=0Then
  61. Echo("""checked"":""true""")
  62. Else
  63. Echo("""checked"":""false""")
  64. EndIf
  65. Echo("}")
  66. Ifi<LsThen
  67. Echo(",")
  68. EndIf
  69. Next

  70. Echo("]}")
  71. EndIf
  72. FunctionEcho(str)
  73. Response.Write(str)
  74. EndFunction
  75. %>

由于4.x有了重大更新,所以很多在3.x中的东西在4.x里并不好使,直接导致了本文迟迟没有发表,原因就出在了更新下拉框后,Grid中显示的是ID号而不是name值。一番查看API及研究,终于发现问题所在,3.x中renderer combobox在4.x并不好用,最后重新读了一遍自己写的代码,才有所顿悟。希望文章能起到一个抛砖引玉的作用,大家一起进步。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值