`
babydeed
  • 浏览: 235550 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

ext2 grid 封装 (包含增删改查 导入导出等操作)

    博客分类:
  • Ext
 
阅读更多

最近项目又用到ext 比较杯具的是ext版本使用2.0

初步封装了一下grid(还在完善中)              ext技术交流群:164648099

 

取一行所有信息通用函数

Ext.override(Ext.grid.GridView,{
	getRecord:function(grid,rowIndex){
		 var self = this;
		 var colNum = grid.colModel.config.length;
		 var obj = {};
		 for(var i = 0;i<colNum ;i++){
			var cell = this.getCell(rowIndex,i);
			if(!Ext.isEmpty(grid.colModel.config[i].dataIndex)){
				obj[grid.colModel.config[i].header]=Ext.util.Format.stripTags(cell.childNodes[0].innerHTML);
			}
		 }

		return obj
	}
});

 

/**
 * @Title:Giasmanage
 * @Description:封装的综合的Grid控件,继承新增、修改、删除、检索、分页、导入、导出等功能
 * @Copyright:Copyright 2012 Beijing GICOM Network Inc. 
 * @author:babydeed
 * @version:1.1
 * @since 2012-5-28
 */ 
Ext.namespace("Ext.ux.grid");
Ext.ux.grid.MyGrid = Ext.extend(Ext.grid.GridPanel, {
	// 储存表格结构
	structure : '',
	
	//是否刚进页面就加载store
	autoloadStore:true,

	//是否有关闭按钮
	closable:true,
	
	// 表格绑定的表
	tablename : '',
    
	border:false,
	
	// 指定加载的列 默认为读取表上所有列数据
	fields : '',

	// 每页显示条数
	pageSize : 20,
	
	// 表单里控件的默认宽
	fieldwidth : 200,

	// reader类型如果当为json的时候那么url不能空,当为array的时候dataObject不能为空
	readType : 'json',

	//是否显示右键详细信息
	showDetailInfo:true ,
	
	// 获取数据的URL
	url : '',
	
	// 新增的URL
	addUrl : "",

	// 修改的URL
	updateUrl : "",

	// 删除的URL
	delUrl : "",
	
	// 导出的URL
	exportUrl : "",
	
	// 导入的URL
	importUrl : "",
	
	// 数据对象
	dataObject : null,

	// 表格主键
	keyField : '',

	// 绑定查询的列
	findField : null,
	
    //查询最大可输入长度
	findFieldMaxLength:20,
	// 是否需要分组,默认为false,如果设置为true须再设置两个参数一个为myGroupField和myGroupTextTpl
	needGroup : false,
	
	// 分组的字段名称
	myGroupField : '',
	// 分组显示的模板,eg:{text} ({[values.rs.length]} {[values.rs.length > 1 ?
	// "Items" : "Item"]})
	myGroupTextTpl : '',

	// 列模式的选择模式,默认为rowselectModel,如果相设置成check模式,就设置为check
	selectType : '',

	// 默认排序字段
	defaultSortField : 'id',

	// 是否需要分页工具栏,默认为true
	needPage : true,
	
	ejectForm : null,

	// 是否带展开按钮,默认为false
	collapsible : false,
	
	//是否显示加载条
	loadMask : true,
	
	//多字段时 保存old属性和值
	mutiKeyValus:{},
	
	//单条件查询控件
	oSingleSearchField:"",
	
	addAfterAopFun:null,
	
	viewConfig : {
		forceFit : true
	},
	// 存储表头信息
	col : null,
	
	storeType:"common",
	
	//是否显示底部分页工具栏的displayInfo属性
	isShowPageTbarInfo:true,
	
	//增删改查提交的默认参数
	actionBaseParams:{add:"",del:"",update:"",query:""},
	
	otherRightMenus:"",
	
	itemGrant:{addIsShow:true,delIsShow:true,updateIsShow:true},
	
	isShowMoreQuery:false,
	
	initComponent : function(config) {
		Ext.apply(this,config);
		if (this.structure != '') {
			this.initGrid();
		}
		
		this.initRightMenu();
		Ext.ux.grid.MyGrid.superclass.initComponent.call(this,config);
	},
	
	// 初始化事件
	initEvents : function() {
		Ext.ux.grid.MyGrid.superclass.initEvents.call(this);
		var button = Ext.query("[class=x-btn-text grid_query]",this.el.dom)[0];// 查询按钮
		var keys = {
			key : Ext.EventObject.ENTER,
			fn : function(key,p) {
				try{
					//var button = Ext.query("[class=x-btn-text grid_query]",this.el.dom)[0];
					if(button){
						button.click();
					};
				}catch(e){
				
				}
			},
			//作用域
			scope : this.getTbar() 
		};
		
		if(!this.keyMap && button){
            this.keyMap = new Ext.KeyMap(this.getTbar(),keys);
        }
	},
	
	destroy:function(){
		try{
        	this.structure=null;
        	this.actionBaseParams=null;
        	this.actionMode = null;
        	this.addAfterAopFun = null;
        	this.delUrl = null;
        	this.closable = null;
        	this.tablename = null;
        	this.border = null;
        	this.pageSize = null;
        	this.fields = null;
        	this.fieldwidth = null;
        	this.myGroupField = null;
        	this.myGroupTextTpl = null;
        	this.findFieldMaxLength = null;
        	this.needGroup = null;
        	this.needPage = null;
        	this.isShowMoreQuery = null;
        	this.itemGrant = null;
        	this.otherRightMenus = null;
        	this.isShowPageTbarInfo = null;
        	this.storeType = null;
        	this.col = null;
        	this.oSingleSearchField = null;
        	this.mutiKeyValus = null;
        	this.ejectForm = null;
        	this.defaultSortField = null;
        	this.selectType = null;
        	this.findField = null;
        	this.findFieldMaxLength = null;
        	this.keyField = null;
        	this.dataObject = null;
        	this.addUrl = null;
        	this.url = null;
        	this.delUrl = null;
        	this.updateUrl = null;
        	this.importUrl = null;
        	this.exportUrl = null;
        	this.readType = null;
        	this.autoloadStore = null;
        	this.keyMap = null;
        	Ext.ux.grid.MyGrid.superclass.destroy.apply(this,arguments);
        	CollectGarbage();
        }catch(e){
        
        }
        
    },
    
	initGrid : function() {
		//生成列模型和record
		var oCmAndRecord =  this.getCmAndRecord();
		// 生成columnModel
		if(this.cmPlugin){
			oCmAndRecord.cm.insertAt(this.cmPlugin,1);
		}
		
		this.colModel  = new Ext.grid.ColumnModel(oCmAndRecord.cm);
		// 默认可排序
		this.colModel.defaultSortable = true;
		// 生成表格数据容器
		var record = Ext.data.Record.create(oCmAndRecord.record);
		// 判断读取类别,目前只实现了,jsonreader和arrayReader 大多数下一般是jsonreader
		
		//var tablename = this.tablename;
		var pageSize = this.pageSize;
		var fields = this.fields;

		var findField = this.findField;
		
		//this.findFieldText = this.colModel.getColumnHeader( this.colModel.findColumnIndex(findField) );
		
		this.initStore(record);

		// 判断是否需要分组
		this.viewConfig  = this.myGridView||this.needGroup?this.getGroupingView():new Ext.grid.GridView({
				forceFit : true
		 });
		 
		// 生成底部分页工具栏
		if (this.needPage) {
			this.bbar = this.getBbar();
			this.bottomToolbar = this.bbar;
		}
		
		//顶部工具栏
		this.tbar = this.getTbar();
		
		//如果配置为了修改url才给每行加监听
		if(this.updateUrl){
			this.on('rowdblclick',this.doEdit.createDelegate(this,[this.keyField]));   
		}
		
		this.store.on('beforeload', function() {
					if(this.oSingleSearchField){
						var searchValue = this.oSingleSearchField.getValue();
						var findField = this.findField;
						var para = {};
						para[findField] = searchValue
						Ext.apply(this.store.baseParams, para);
					}
					
					Ext.apply(this.store.baseParams, this.actionBaseParams.query);

		},this);

		if(this.autoloadStore){
			this.store.load({
				params : {
					start : 0,
					limit : this.pageSize
				}
			});
			
		}
	}
		
});
Ext.ux.grid.MyGrid.prototype.getGroupingView = function(){
			return new Ext.grid.GroupingView({
						forceFit : true,
						groupTextTpl : this.myGroupTextTpl||'{text}(共{[values.rs.length]}条)'
			})
};

Ext.ux.grid.MyGrid.prototype.formatDate = function(v) {
		   return v ? v.dateFormat('Y-m-d') : ''
};

Ext.ux.grid.MyGrid.prototype.doSuccess = function(action, form) {
			Ext.MessageBox.hide();
			Ext.Msg.alert('提示', '操作成功');
			this.getStore().reload();
};

Ext.ux.grid.MyGrid.prototype.doFailure = function(action, form) {
			Ext.MessageBox.hide();
			Ext.Msg.alert('请求错误', '服务器未响应,请稍后再试');
};

	/*
	* @功能:删除所有选中记录支持批量删除
	* 
	*/
Ext.ux.grid.MyGrid.prototype.doDelete = function() {
		this.deleteUtil(this.delUrl,this,this.keyField);
};
	/*
	* @功能:增加和删除调用的函数
	* 
	*/
Ext.ux.grid.MyGrid.prototype.doEdit = function(id) {
			
		var tablename = this.tablename;
		
		//var keyField = this.keyField;
		var keyFields = this.keyField.split(",")
		
			var url = this.url;
			var ogrid = this;
			var oField = new Array();
			var len = this.structure.length;
			var action = "";
	
		    // 判断id是否为空 是:新增 否:修改
		    this.AddOrUpdateUrl = id ? this.updateUrl: this.addUrl;
		    var action = id?"edit":"add";
		    var titleMsg = "增加";
		    var params = this.actionBaseParams.add;
		    if (action=="edit") {
		    	var count = this.getSelectionModel().getSelections().length;
		    	if(count>1){
		    		Ext.Msg.alert("系统提示","只能编辑一条数据");
		    		return;
		    	}else if(count==0){
		    		Ext.Msg.alert("系统提示","请选择一条数据进行编辑");
		    		return;
		    	}
		    	titleMsg = "修改";
		    	params = this.actionBaseParams.del;
		    }
		    
		    //第一次进入判断 如果弹出的form不为空 则使用自定义的form 同时为当前grid.ejectForm 赋上值;如果弹出的form为空 则走else
		    //第>=2次进入判断 则始终走if语句
			if(!Ext.isEmpty(this.ejectForm) ){
					var win = this.getEjectWin();
					win.setTitle(titleMsg);
			}else{
				oField = MyExt.formUtil.getForm(this.structure);
				// ------------- 初始化字段信息 结束------------
				// 初始化表单结构
				this.ejectForm = new Ext.form.FormPanel({
										labelWidth : this.formLabelWidth||80, 
										frame : true,
										scope:this,
										border : false,
										hideBorders : true,
										autoHeight : true,
										items : oField,
										buttons : [
												{
													text : '保存',
													scope:this,
													handler : function() {
														this.doSubmitFrom(this.AddOrUpdateUrl,params);
														//doSubmitFrom.call(this,this.AddOrUpdateUrl);
													}
												}, {
													text : '关闭',
													scope:this,
													handler : function() {
														this.ejectWin.hide();
														//this.ejectWin.destroy();
													}
												}
										]
						})
					var win = this.getEjectWin();
					win.setTitle(titleMsg);
			}
			
			this.mutiKeyValus = {};
			win.show();
			
			if (this.addAfterAopFun&&action=="add") {
				this.addAfterAopFun();
			}
			
			this.changeFormItemIsReadOnly(this.ejectForm.form,this.structure,action);
	
			// 从服务器初始化表单数据
			if (id != null && id != '') {
				Ext.MessageBox.wait('正在数据加载,请稍后......', '请稍后')
				  	var record = this.getSelectionModel().getSelected();//获取选择的记录集
	                var oldKeyids={};
	                if(keyFields.length>1){
		                for(var k = 0;k < keyFields.length; k++){
		                	var oldName = keyFields[k]+"Old";
		                	oldKeyids[oldName]=record.get(keyFields[k]);
		                }
		                this.mutiKeyValus = oldKeyids;
	                }
	                this.ejectForm.form.loadRecord(record); //往表单(fp.form)加载数据
	                Ext.MessageBox.hide();
					
			}
};

//=========================================================================
//  初始化grid导入的操作代码
//=========================================================================
Ext.ux.grid.MyGrid.prototype.doImport = function(){
		     var form = new Ext.form.FormPanel({    
												     labelAlign: 'center',    
												     labelWidth:60,   
												     frame:true, 
												     url: this.importUrl,  
												     width: 300,    
												     border:false,
												     bodyStyle:"margin-top:30",  
												     height:100,   
												     fileUpload: true,//这项一定要要,表是是上传文件   
												     items: [{  
												        xtype: 'textfield', 
												        fieldLabel: '文件路径',    
												        name: 'filePath',    
												        inputType: 'file'//文件类型    
												     }],    
												     buttons: [{    
												        text: '导入',
												        scope:this,    
												        handler: function() {
												        if(form.getForm().isValid() && checkFiletype(form)){
													        var reg=/\\+/;//获取文件名,主要为了区别IE,FireFox
													        var filePath = form.form.findField("filePath").getValue();
													       // alert(filePath)
													       Ext.Msg.show({
															   title: '系统提示',
															   msg: '<font color=black>正在导入中...</font>',
															   width: 250,
															   wait:true,
															   mode:true,
															   progress:true,
															   closable:false  
															});
													        Ext.Ajax.request({
													        	waitMsg:"文件上传中......",  
																url : this.importUrl,
																scope:this,
																form:form.form.id,
																success : function(response) {
																	Ext.MessageBox.hide();
																	var result = Ext.decode(response.responseText);
																	if(result.success){
																		this.getStore().reload();
																		excelWin.hide();
																		new Ext.ux.Notification({autoHide:true}).showSuccess('提示', result.msg);
																	}else{
																		new Ext.ux.Notification().showFailure('提示', result.msg);
																	}
																},
																failure : function(form,action){
																	Ext.MessageBox.hide();
																	new Ext.ux.Notification().showFailure('操作失败','导入失败,请重新导入'); 
																}
															});//endof ajax
							
							
												        
													    /* form.getForm().submit({  
													        waitMsg:"文件上传中......",  
													        success: function(form, action){ 
													        		alert(11);
															        if (action.result.success) {
															        	new Ext.ux.Notification({autoHide:true}).showSuccess('操作成功','文件上传成功!');
															        }else{
																		new Ext.ux.Notification().showFailure('操作失败',action.result.msg);
																	}
													        },    
													        failure: function(form,action){
														          alert("失败")
														          if(action.result.head==2044){
														          	new Ext.ux.Notification().showFailure('操作失败','令牌序列号插入冲突,请重新插入'); 
														          }else{
														          	new Ext.ux.Notification().showFailure('错误', '文件上传失败'); 
														          }
													          
													        }    
												     	});  */
												    } 
												    }   
												  }
										  ]    
										  });  
										excelWin = new Ext.Window({
											    width:310,
											    shadow:false,
											    title:"Excel导入",
												autoHeight:true,
											    resizable:false, 
											    constrain:true, 
											    closeAction:'hide',//点击右上角关闭按钮是动作是把win隐藏
											    layout:'fit',
											    closable:true,
											    modal:true, 
									    	    items:[form]
									     })
									     excelWin.show();   
										 checkFiletype = function(form){
										  	var epath = form.form.findField("filePath").getValue();
										  	if (epath.substring(epath.lastIndexOf(".") + 1).toLowerCase() == "xls" || 
										  		epath.substring(epath.lastIndexOf(".") + 1).toLowerCase() == "xlsx"){
										  		return true;
										  	}else{
										  		new Ext.ux.Notification().showFailure('错误', '只允许导入excel文件'); 
										  		return false;
										  	}
				}
}
//=========================================================================
//  初始化grid的store
//=========================================================================
Ext.ux.grid.MyGrid.prototype.initStore = function(record){
				switch (this.readType) {
					case 'json' :
						var reader = new Ext.data.JsonReader({
									totalProperty : "total",
									root : "list",
									id : this.keyField,
									baseParams :this.storeBaseParams
								// 关键字段
								}, record);
						if(this.storeType=="common"){
							this.store = new Ext.data.Store({
											proxy : new Ext.data.HttpProxy({
											url : this.url
										}),
										reader : reader,
//										sortInfo : {
//											field : this.defaultSortField,
//											direction : 'ASC'
//										},
										//remoteSort : false,
										remoteSort:this.cmRemoteSort||false//是否后台排序
										//,groupField : this.myGroupField || this.defaultSortField
										/*,listeners : {
											'loadexception' : function() {
												alert('reload')
											}
										}*/
							});
						}else{
							this.store = new Ext.data.GroupingStore({
											proxy : new Ext.data.HttpProxy({
											url : this.url
										}),
										reader : reader,
										sortInfo : {
											field : this.defaultSortField,
											direction : 'ASC'
										},
										remoteSort:this.cmRemoteSort||false,//后台排序
										groupField : this.myGroupField || this.defaultSortField
										/*,listeners : {
											'loadexception' : function() {
												alert('reload')
											}
										}*/
							});						
						}

						break;
					case 'array' :
						var reader = new Ext.data.ArrayReader({}, record);
						this.store = new Ext.data.GroupingStore({
							reader : reader,
							data : this.dataObject,
							sortInfo : {
								field : this.defaultSortField,
								direction : 'ASC'
							},
							groupField : this.myGroupField
						});
						break;
					default :
						break;
				}//endof swith
};
//=========================================================================
//  初始化grid右键菜单
//=========================================================================
Ext.ux.grid.MyGrid.prototype.initRightMenu = function(){
			if(!this.myRightMenu){
				this.myRightMenu =  new Ext.menu.Menu({
						        items: [
							        		
						       		   ]
				});
				
				if(this.showDetailInfo){
				 	this.myRightMenu.add({iconCls:"user-detail-icon",text:"显示详细信息",scope:this,handler:function(){
				 			var index = this.getStore().indexOf(this.getSelectionModel().getSelected());
				 			if(this.showDetailInfoIsGrid){
									var obj = this.getView().getRecord(this,index);
									var grid = new Ext.grid.PropertyGrid({
										        autoHeight:true,
										        width: 300,
										        autoScroll:true,
										        source: obj,
										        listeners:{
										        	"beforeedit":function(e) {
															e.cancel = true;
															return false; 
													}
										        }
									});
							  		var win = new Ext.Window ({
							  			title:"详细信息",
							  			items:grid,
							  			layout:"fit",
							  			width:460,
							  			autoScroll:true, 
							  			autoHeight:true,
										draggable:true,
										modal:true, 
										resizable:false,
							  			closeAction:"close",
							  			buttonAlign:"center",
							  			buttons:[{text:"关闭",iconCls:'close',handler:function(){
							  				this.ownerCt.close();
							  			}}]
							  		}).show();				 			  
				 			  }else{
				 			  		var items = MyExt.formUtil.getReadOnlyForm(this.structure,100);
									var win = new MyExt.win.commonWin({
								 					width : 450,
								 					title:"详细信息",
								 					layout:"fit",
								 					items : items,
								 					closeAction:"hide",
								 					buttons:[
								 						{text:"关闭",handler:function(){
								 							this.ownerCt.close();
								 						}}
								 					]
									});	
									win.show();
		 							var obj = this.getView().getRecordOfName(this,index);
		 							win.items.item(0).form.setValues(obj);
				 			  }
							
						}
					})
				 }
				 
				if(!Ext.isEmpty(this.addUrl)){
					if(this.itemGrant.addIsShow){
						this.myRightMenu.add({iconCls:"user-add-icon",text:this.addText||"增加",scope:this,handler:function(){
								this.doEdit();
							}
						})
					}
				 }
				 if(!Ext.isEmpty(this.updateUrl)){
				 	if(this.itemGrant.updateIsShow){
						this.myRightMenu.add({iconCls:"user-edit-icon",text:this.addText||"修改",scope:this,handler:function(){
								this.doEdit(this.keyField);
							}
						})
					}
				 }
				 
				 if(!Ext.isEmpty(this.delUrl)){
				 	if(this.itemGrant.delIsShow){
						this.myRightMenu.add({iconCls:"user-delete-icon",text:this.delText||"删除",scope:this,handler:function(){
								this.doDelete();
							}
						})
					}
				 }
				 if(!Ext.isEmpty(this.importUrl)){
					this.myRightMenu.add({iconCls:"user-export-icon",text:"导入",scope:this,handler:function(){
							this.doImport();
						}
					})
				 }
				 
				 if(!Ext.isEmpty(this.exportUrl)){
					this.myRightMenu.add({iconCls:"user-export-icon",text:"导出",scope:this,handler:function(){
							MyExt.util.exportCurentTable(this,this.exportUrl,this.title||"导出文件");
						}
					})
				 }
				 
				 if(!Ext.isEmpty(this.otherRightMenus)){
				 	for(var i = 0;i<this.otherRightMenus.length;i++){
				 		this.myRightMenu.add(this.otherRightMenus[i])
				 	}
				 }
			}
		
				  		
	  		if(!this.hasListener("rowcontextmenu")){
	  			if(this.myRightMenu.items.length!=0){
			  		this.on("rowcontextmenu",function(grid, rowIndex, e){
				        		e.preventDefault();
						        grid.getSelectionModel().selectRow(rowIndex);
						        this.myRightMenu.showAt(e.getXY());
				    });
	  			}
	  		}
};//endof 右键

//=========================================================================
//  获得底部工具栏
//=========================================================================
Ext.ux.grid.MyGrid.prototype.getBbar = function(){
				var butItems = [];
				if (this.addUrl) {
						if(this.itemGrant.addIsShow){
							butItems.push({
									iconCls : 'user-add-icon',
									text : "增加新数据",
									scope:this,
									handler : function() {
										this.doEdit();
									}
							});
							butItems.push('-');
						}
				};
				if (this.updateUrl) {
						if(this.itemGrant.updateIsShow){
							butItems.push({
									iconCls : 'user-edit-icon',
									text : "编辑当前数据",
									scope:this,
									handler : function() {
											var record = this.getSelectionModel().getSelected();
											if (record == null) {
												Ext.Msg.alert('提示', '请先选择你要编辑的数据');
												return;
											}
											//var id = record.get(this.keyField);
											//alert(id);
											this.doEdit(this.keyField);
									}
							});
							butItems.push('-');
						}
				};
				if (this.delUrl) {
					if(this.itemGrant.delIsShow){
						butItems.push({
								iconCls : 'user-delete-icon',
								text : "删除所选数据",
								scope:this,
								handler : function() {
									this.doDelete();
								}
						});
						butItems.push('-');
					}
				};
				
				if(this.exportUrl){
					butItems.push({
							iconCls : 'exportToExcel',
							text : "导出数据",
							scope:this,
							handler:function(){
								MyExt.util.exportCurentTable(this,this.exportUrl,this.title||"导出文件");
							}
							/*menu:new Ext.menu.Menu({
							items:[
										{iconCls:"exportToExcel",scope:this,text:"导出当前页",handler:function(){	
											alert(this.exportUrl);
										 }},
										{iconCls:"exportToExcel",text:"导出当前表",handler:function(){	
				
										}}
						    	 ]
							}) */
					})
				}
				if(this.importUrl){
					butItems.push({
						iconCls : 'exportToExcel',
							text : "导入数据",
							scope:this,
							handler : function() {
								//	alert(this.importUrl);
								this.doImport();
						}
					})
				}
				var tbar = null;
				if(this.isShowPageTbarInfo==false){
					tbar = new Ext.PagingToolbar({
								pageSize : this.pageSize,
								displayInfo :false,
								displayMsg : '当前记录数:{0} - {1} 总记录数: {2}',
								emptyMsg : '没有符合条件的记录',
								store : this.store,
								items:butItems
					});
				}else{
					tbar = 	new Ext.PagingToolbar({
							pageSize : this.pageSize,
							displayInfo : Ext.isEmpty(this.displayInfo)?true:false,
							displayMsg : '当前记录数:{0} - {1} 总记录数: {2}',
							emptyMsg : '没有符合条件的记录',
							plugins:new Ext.ux.Andrie.pPageSize(),
							//plugins:new Ext.ux.PageComboResizer(),
							store : this.store,
							items:butItems
						});
				}
			return tbar;
};
		
//=========================================================================
//  获得顶部工具栏
//=========================================================================		
Ext.ux.grid.MyGrid.prototype.getTbar = function(){
				if(this.tbar){
					return this.tbar;
				}
				//如果是单字段主键查询
				else if(!Ext.isEmpty(this.findField)&&Ext.isEmpty(this.tbar)&&Ext.isEmpty(this.tbarQueryItem)){
					var tbarArray = [];
					
					this.oSingleSearchField = new Ext.ux.form.SearchField({
						store : this.store,
						paramName:this.findField,
						maxLength:this.findFieldMaxLength,
						width:150
					});
					var cm = this.getColumnModel();	
					tbarArray.push(cm.getColumnHeader(cm.findColumnIndex(this.findField)));
					tbarArray.push(":");
					tbarArray.push(this.oSingleSearchField);
					
					var tbar =  new Ext.Toolbar({items:tbarArray});
					return tbar;
				}
				//如果是自定义多字段查询
				else if(!Ext.isEmpty(this.tbarQueryItem)){
					var tbarArray = [];
					var item = MyExt.formUtil.getTbarQueryItem(this.structure,this.tbarQueryItem);
					tbarArray = tbarArray.concat(item);
					//alert(item.length);
					tbarArray.push("&nbsp;&nbsp;&nbsp;")
					tbarArray.push(
							new Ext.Button({scope:this,iconCls:"grid_query",text:'查询',listeners:{
								click:function(){
									var tbarPara = MyExt.formUtil.getTbarValues(this.getTopToolbar());
								
									Ext.apply(this.store.baseParams,tbarPara)
									
									if(this.theTwoQueryTbar){//如果含有第2层tbar
										var theTwoQueryBar = MyExt.formUtil.getTbarValues(this.theTwoQueryTbar);
										Ext.apply(this.store.baseParams,theTwoQueryBar)
									}
									
									var store = this.store;
									
									store.load({
														params : {
															start : 0,
															limit : 20
														}
									});
								
								},
								scope:this
								
							}
						})
					);
					tbarArray.push("-");
					
					if(this.isShowMoreQuery){
							this.showMoveQueryButton =	new Ext.Button({scope:this,iconCls:"queryMore",text:'显示更多查询条件',handler:function(){
									if(!this.theTwoQueryTbar){
										var tbarArray = [];
										var item = MyExt.formUtil.getTbarQueryItem(this.structure,this.tbarMoveQueryItem);
										tbarArray = tbarArray.concat(item);
										this.theTwoQueryTbar =  new Ext.Toolbar({items:tbarArray});
										var width = this.getSize().width;
										this.theTwoQueryTbar.render(this.tbar);
										this.setHeight(this.getSize().height-this.theTwoQueryTbar.getSize().height)
										this.setWidth(width);
										this.showMoveQueryButton.setText("关闭更多查询条件");
									}else{
										if(this.theTwoQueryTbar.isVisible()){
											var grid = this;
											MyExt.formUtil.setTbarValuesNull(grid.theTwoQueryTbar);
											var width = this.getSize().width;
											var height = this.theTwoQueryTbar.getSize().height;
											this.theTwoQueryTbar.hide();
											this.setHeight(this.getSize().height+height);
											this.setWidth(width);
											this.showMoveQueryButton.setText("显示更多查询条件");
										}else{
											var width = this.getSize().width;
											this.theTwoQueryTbar.show();
											var height = this.theTwoQueryTbar.getSize().height;
											this.setHeight(this.getSize().height-height);
											this.setWidth(width);
											this.showMoveQueryButton.setText("关闭更多查询条件");
										}
									}
								}
							});

							tbarArray.push(this.showMoveQueryButton)
							tbarArray.push("-");
					};
					
					tbarArray.push(
						new Ext.Button({scope:this,iconCls:"table_refresh",text:'显示全部',handler:function(){
								var grid = this;
								MyExt.formUtil.setTbarValuesNull(grid.getTopToolbar());
								if(this.theTwoQueryTbar){//如果含有第2层tbar
									MyExt.formUtil.setTbarValuesNull(this.theTwoQueryTbar);
									var para = MyExt.formUtil.getTbarValues(this.theTwoQueryTbar);
									Ext.apply(this.store.baseParams,para)
								}
								var tbarPara = MyExt.formUtil.getTbarValues(grid.getTopToolbar());
								Ext.apply(this.store.baseParams,tbarPara)
								
								this.store.load({
												params : {
													start : 0,
													limit : this.pageSize
												}
								});
							}
						})
					);
					
					var tbar =  new Ext.Toolbar({items:tbarArray});
					return tbar;
				
				}
				
};

//=========================================================================
//   增加和修改最后提交的函数
//=========================================================================		
Ext.ux.grid.MyGrid.prototype.doSubmitFrom =function(url,params){
		if (this.ejectForm.form.isValid()) {
						Ext.apply(this.mutiKeyValus,params);
						Ext.Ajax.request({
								url : url,
								params:this.mutiKeyValus,
								method : 'POST',
								form : this.ejectForm.form.id,
								scope : this,
								waitMsg : '正在保存数据,请等待...', // 显示读盘的动画效果,执行完成后效果消失
								success:function(response){
									var result = Ext.util.JSON.decode(response.responseText);
									if(result.success){
										new Ext.ux.Notification({autoHide:true}).showSuccess('提示', result.msg);
										this.getStore().reload({
												params : {
													start : 0,
													limit : this.pageSize
												}
										});

										this.ejectWin.hide();
									}else{
										new Ext.ux.Notification().showFailure('提示', result.msg);
									}
									//Ext.Msg.alert('提示', '操作成功');
									
								},
								failure : function() {
									new Ext.ux.Notification().showFailure('提示', '操作失败');
									//Ext.Msg.alert('提示', '操作失败');
									//this.loadCurrData();
								}
							});
							
							
					/*ogrid.ejectForm.form.submit({
						waitTitle : "请稍候",
						waitMsg : "正在提交表单数据,请稍候。。。。。。",
						success : function() {
							ogrid.getStore().reload();
							Ext.Msg.alert('提示', '操作成功');
						},
						failure : ogrid.doFailure
						
						});*/
						}
}

//=========================================================================
//  获取增加和修改的window
//=========================================================================
Ext.ux.grid.MyGrid.prototype.getEjectWin =function(){
	if( Ext.isEmpty(this.ejectWin) ){
			this.ejectWin = new Ext.Window({
						title :this.title,
						labelWidth : 100,
						frame : true,
						autoHeight : true,
						//height : 400,
						modal: true,
						//maximizable:true,
						resizable:false,
			            shadow: false,
						closeAction:"hide",
						width : 450
						,items : this.ejectForm	
						,listeners:{
							"hide":function(){
								this.items.item(0).form.reset();
							}
						}	
		})
	}
	return this.ejectWin;
}

//=========================================================================
//  获取列模型和Record
//=========================================================================
Ext.ux.grid.MyGrid.prototype.getCmAndRecord = function(){
				var oCM = new Array(); // 列模式数组
				
				this.readOnlyField = [];
				var oRecord = new Array(); // 容器对数组
				// 构成grid的两个必须组件: column和record,根据structure将这两个组件创建出来
				
				oCM[oCM.length] = new Ext.grid.RowNumberer({width:35});
				// 判断表格的选择模式
				//alert(1);
				if (this.selectType == 'check') {
					var sm = new Ext.grid.CheckboxSelectionModel();
					oCM[oCM.length] = sm;// 在列模式数组中添加checkbox模式按钮
					this.selModel = sm;// 并将selModel设置为check模式
				}else if(this.selectType == 'single'){
					// 在列模式数组中添加single模式按钮
					var sm = new Ext.grid.RowSelectionModel({ singleSelect: true })
					//oCM[oCM.length] = sm;
					this.sm = sm;
				}
				
				var len = this.structure.length;// 得到结构的长度
				
				for (var i = 0; i < len; i=i+1) {
					var c = this.structure[i];
					// alert( c.hidden ? c.width: this.fieldwidth)
					// 如果字段为hidden,则不生成filters和columnMode
					
					// 默认格式化日期列
					//if (c.type == 'date' && !c.renderer) {
					//	c.renderer = this.formatDate;
					//}
					if(c.type == 'label'){
						this.readOnlyField.push({name:c.name,addIsShow:c.addIsShow});
					}
					oCM[oCM.length] = {
						header : c.header,
						dataIndex : c.name,
						hidden : c.hidden || false,
						width : c.width ||this.fieldwidth,
						// 类型为数字则右对齐
						align : c.type == 'numeric' ? 'right' : 'left',
						// 结构的渲染函数
						renderer : c.renderer,
						detailIsShow:c.detailIsShow
					};
			
					oRecord[oRecord.length] = {
						name : c.name,
						mapping:c.name
						// 如果类型不是date型则全部为string型
						//,type : c.type == 'date' ? 'date' : 'string'
						//dateFormat : 'Y-m-d'
					};
				}
				return {cm:oCM,record:oRecord};
}

		
//=========================================================================
//  表格删除方法
//=========================================================================
Ext.ux.grid.MyGrid.prototype.deleteUtil = function(){
			var agru = arguments;
			var argsLen = arguments.length;//参数的长度
			var grid = arguments[1];
			var url = arguments[0];
			var keyIds = arguments[2].split(",");
			var rows  = grid.getSelectionModel().getSelections(); 
			if(Ext.isEmpty(rows)||rows.length==0){
				Ext.Msg.alert("系统提示","请选择要删除的数据");
				return;
			};
			var txt = "您确定要删除";
			try{
				//if(keyIds.length==1){
					var cm = grid.getColumnModel()
					var col = cm.findColumnIndex(keyIds[0])	
					var columnHeader = cm.getColumnHeader(col);
					txt +="<font color=red>";
					txt += columnHeader+":";
					for(var r = 0 ; r<rows.length;r++){
						txt += rows[r].get(keyIds[0]);
						if(r!=rows.length-1){
							txt +=";"
						}
					}
					txt +="</font>";
				//}
					txt +="吗?";
			}catch(t){
				txt = "您确定要删除吗";
			}
			
			Ext.MessageBox.confirm("系统提示",txt,function(btn){
				   		if(btn=="yes"){
							var rows  = grid.getSelectionModel().getSelections(); 
							var rowsLen = rows.length;
							var jsonArray=[];
							for(var i = 0; i < rowsLen; i=i+1) {
								var obj = {};
								for(var j = 0;j<keyIds.length;j=j+1){
									 var a = keyIds[j];
									 obj[a] = rows[i].get(a);
								}
								jsonArray.push(obj);
							}
//							Ext.Msg.show({
//							   title: '系统提示',
//							   msg: '<font color=black>正在删除中...</font>',
//							   width: 250,
//							   wait:true,
//							   mode:true,
//							   progress:true,
//							   closable:false  
//							})
							var params = Ext.apply({deleteIds:Ext.encode(jsonArray)},this.actionBaseParams.del)
							Ext.Ajax.request({
										url:agru[0],
										params:params,
										showWaitMsg:true,										
										method:"POST",
										success:function(response){
											var result = Ext.util.JSON.decode(response.responseText);
											if(result.success){
												grid.getStore().reload();
												new Ext.ux.Notification({autoHide:true}).showSuccess('提示', result.msg);
											}else{
												new Ext.ux.Notification().showFailure('提示', result.msg);
											}
										}
							});
				        }
				},this)
};
Ext.ux.grid.MyGrid.prototype.changeFormItemIsReadOnly = function(form,array,action){
	for(var i = 0, len = array.length; i < len; i=i+1){
                var f = form.findField(array[i].name);
                var addIsShow = array[i].addIsShow;
                var editIsReadOnly = array[i].editIsReadOnly;
                var editIsShow = array[i].editIsShow;
                
                if(f){
			        if(action=="add"){   //如果是增加
				        	
				        	if(addIsShow==true||Ext.isEmpty(addIsShow)){   //如果是该字段要显示
				        		f.show();
				        		f.removeClass("x-item-disabled");
				        		f.getEl().up('.x-form-item').setDisplayed(true); 
				        	}else if(addIsShow==false){ 				//如果不需要显示
				        		f.hide();                   
				        		f.getEl().up('.x-form-item').setDisplayed(false); //隐藏序号id
				        		f.addClass("x-item-disabled");
				        	}
				        	
				        	if(f.getXType()!="combo"){
				        		if(f.rendered){
						           f.el.dom.readOnly = false;
						           //f.el.dom.style.background = "#E5E5E5";
						        }else{
						       	 	f.readOnly = false;
						        }
				        	};

					        
			         }else if (action=="edit"){		//如果是修改
			          		if(editIsReadOnly == true){
			          				f.show();
			          				f.getEl().up('.x-form-item').setDisplayed(true); //隐藏序号id
			          				f.addClass("x-item-disabled");
				          			if(f.rendered){
							           f.el.dom.readOnly = true;
							        }else{
							       	 	f.readOnly = true;
							        }
							        
			          		}else if(editIsReadOnly == false){            //此行可能删除if括号内判断
			          				f.removeClass("x-item-disabled");
			          				f.show();
			          				if(f.getXType()!="combo"){
				          				if(f.rendered){
								           f.el.dom.readOnly = false;
								        }else{
								       	 	f.readOnly = false;
								        }
							        }
							        
			          		}
			          		
			          		if( editIsShow == true ){
			          				f.show();
			          				f.removeClass("x-item-disabled");
			          				f.getEl().up('.x-form-item').setDisplayed(true); //隐藏序号id
			          				if(f.rendered){
							           f.el.dom.readOnly = false;
							        }else{
							       	 	f.readOnly = false;
							        }
			          			
			          		}else if( Ext.isEmpty(editIsReadOnly) && editIsShow==false ){
			          			f.getEl().up('.x-form-item').setDisplayed(false); //隐藏序号id
			          			f.hide();
			          		}
			          	}	
			         } //if结束
    }//for循环结束
}
//右键显示详细信息是否是grid 否则是form
Ext.ux.grid.MyGrid.prototype.showDetailInfoIsGrid = false;

 

 

上面代码中还会用到附件utils.rar中的某些方法

以上代码不断完善中,如有错误请指正,谢谢!

 

 

 

另附ext技术交流群:164648099

 

 

附件还包含群友翻译的“extjs4.0手册翻译.rar”     感谢“天渡云”朋友

3
0
分享到:
评论
1 楼 zy463395598 2012-04-19  
thanks la

相关推荐

Global site tag (gtag.js) - Google Analytics