extjs中的formPanel以及表单的应用

var grid;

Ext.onReady(function() {

	// grid中的复选框
	var sm = new Ext.grid.CheckboxSelectionModel();
	// 数据存储器
	var ds = new Ext.data.Store({
				proxy : new Ext.data.HttpProxy({
							url : "../student.action?method=page",
							method : "post"
						}),
				reader : new Ext.data.JsonReader({ // 读取json数据
					root : "newsList",
					totalProperty : 'totalProperty' // 总记录数
				}, [{
							name : "id"
						}, {
							name : "name"
						}, {
							name : "sex"
						}, {
							name : "birthday"
						}, {
							name : "by1"
						}])
			});
	function toChin(val){
		if(val=="1"){
			 return "男";
		}else{
			return "女";
		}
	}
	
	// 创建列
	var cm = new Ext.grid.ColumnModel([
			sm, // 复选框
			{
				header : "编号",
				dataIndex : "id",
				sortable : true
			}, {
				header : "姓名",
				dataIndex : "name",
				width : 100
			}, {
				header : "性别",
				dataIndex : "sex",
				width : 110,
				renderer : toChin
			}, {
				header : "出生日期",
				dataIndex : "birthday",
				width : 150
			}, {
				header : "民族",
				dataIndex : "by1",
				width : 110
			}]);
	cm.defaultSortable = true;// 默认可排序

	// grid中的工具条
	var toolbar = new Ext.Toolbar([{
				text : '添加',
				icon : 'icons/add.gif',
				handler : function() { 
					insertform.form.reset();  //添加前先重置表单
					window_add.show();
				}
			}, {
				text : '修改',
				icon : 'icons/edit.gif',
				handler : function() {
					loadUpdateForm();
				}
			}, {
				text : '删除',
				icon : 'icons/delete.gif',
				handler : function() {
					// 获取选中的对象
					var list = grid.getSelectionModel().getSelections();
					var str = '';
					if (list.length > 0) {
						for (var i = 0; i < list.length; i++) {
							str = str + list[i].get('id') + ',';
						}
					}
					Ext.Msg.alert("提示", "删除" + str);

					var idList = [];
					for (var i = 0; i < list.length; i++) {
						idList.push(list[i].get('id'));
					}
					for (var i = 0; i < idList.length; i++) {
						var index = ds.find('id', idList[i]);
						if (index != -1) {
							var rec = ds.getAt(index);
							ds.remove(rec); // 移除
						}
					}

				}
			}, {
				text : '重新加载',
				icon : 'icons/plugin.gif',
				handler : function() {
					ds.reload();
				}
			}]);

	// 创建Grid
	grid = new Ext.grid.GridPanel({
				el : "grid",
				ds : ds,
				title : "代码列表",
				width : 600,
				height : Ext.get("content").getHeight() / 2 + 20,
				cm : cm,
				loadMask : {
					msg : '正在加载数据,请稍侯……'
				},
				sm : sm,
				tbar : toolbar,
				// 下边
				bbar : new Ext.PagingToolbar({
							pageSize : 10,
							store : ds,
							displayInfo : true,
							displayMsg : ' 显示第 {0} 条到 {1} 条记录,一共 {2} 条',
							emptyMsg : ' 没有记录'
						})
			});
	grid.render(); // 组件渲染之后触发
	ds.load({params : {start : 0,limit : 10}}); // 加载数据

	// 双击事件
	grid.addListener("rowdblclick", function(grid, rowIndex, columnIndex, e) {
				var dataObj = grid.getStore().getAt(rowIndex); // 说去选中的行的数据对象
				var id = dataObj.get("id");
				var content = dataObj.get("name");
				Ext.Msg.alert("提示", id + content);
			});

		// 单击事件
		/*
		 * grid.addListener("click",function(){ Ext.Msg.alert("提示","单击事件"); });
		 */

		/*
		 * 如果要动态加载grid数据则,在方法内加入 ds:数据存储器,propertyId为要传的参数
		 * ds.load({params:{start:0,limit:10,propertyId:propertyId}});
		 * 
		 */

	});
 
/**
	 * 分页读取Grid内容
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(params = "method=page")
	public ModelAndView page(HttpServletRequest request,
			HttpServletResponse response) {
		int start;
		try {
			start = Integer.parseInt(request.getParameter("start"));
		} catch (NumberFormatException e1) {
			start = 0;
		}
		int limit;
		try {
			limit = Integer.parseInt(request.getParameter("limit"));
		} catch (NumberFormatException e1) {
			limit = 10;
		}
		Student nr = new Student();
		List<Student> list = studentService.findStudentByPage(nr, start, limit);
		int totalProperty = studentService.findByCont();
		JSONArray jsonArray = new JSONArray();
		Iterator ite = list.iterator();
		while (ite.hasNext()) {
			Student s = (Student) ite.next();
			Map map = new HashMap();
			map.put("id", s.getId());
			map.put("name", s.getName());
			map.put("sex", s.getSex());
			map.put("birthday", s.getBirthday());
			map.put("by1", s.getBy1());
			jsonArray.add(map);
		}
		String jsonStr = jsonArray.toString();
		String jsonString = "{start:" + start + ",limit:" + limit
				+ ",totalProperty:" + totalProperty + ",newsList:" + jsonStr
				+ "}";
		response.setContentType("text/html;charset=utf-8");
		try {
			response.getWriter().write(jsonString);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return null;
	}
 
// 定义Grid中的行对象
var Student = Ext.data.Record.create([{
			name : 'id',
			mapping : 'id',
			type : 'int'
		}, {
			name : 'name',
			mapping : 'name',
			type : 'string'
		}, {
			name : 'sex',
			mapping : 'sex',
			type : 'string'
		}, {
			name : 'birthday',
			mapping : 'birthday',
			type : 'string'
		}, {
			name : 'by1',
			mapping : 'by1',
			type : 'string'
		}]);

		//读取下拉列表内容
var ds = new Ext.data.Store({
			proxy : new Ext.data.HttpProxy({
						url : '../student.action?method=selectTree'
					}),
			reader : new Ext.data.JsonReader({}, ['code', 'content'])
		});

var insertform = new Ext.FormPanel({
	frame : true,
	labelWidth : 70,
	bodyStyle : 'padding:5px',
	border : false,
	labelAlign : 'right',
	fileUpload : true, // 上传文件(必填)
	items : [{
		layout : 'column',
		border : false,
		items : [{
			columnWidth : .5,
			layout : 'form',
			baseCls : 'x-plain',
			border : false,
			// defaultType : 'textfield',
			defaults : {
				anchor : '80%'
			},
			items : [{
						fieldLabel : '身份证号',
						xtype : 'textfield',
						name : 'idCard',
						maxLength : 50
					}, {
						fieldLabel : '姓名',
						xtype : 'textfield',
						name : 'name'
					}, {
						fieldLabel : '电子邮件',
						xtype : 'textfield',
						name : 'email',
						vtype : 'email'
					}, {
						xtype : 'panel',
						layout : 'table',
						fieldLabel : '性别',
						defaultType : 'radio',
						isFormField : true,
						items : [{
							name : 'sex',
							boxLabel : '<span style="color:black;font-size:12px;">男&nbsp;&nbsp;</span>',
							inputValue : '1',  //值
							checked : true  //默认选中
						}, {
							name : 'sex',
							boxLabel : '<span style="color:black;font-size:12px;">女</span>',
							inputValue : '2'
						}]
					}]
		}, {
			columnWidth : .5,
			layout : 'form',
			border : false,
			defaultType : 'textfield',
			defaults : {
				anchor : '80%'
			},
			items : [{
						store : ds,  //下拉列表的数据
						fieldLabel : '民族',  
						name : 'by1',   
						xtype : 'textfield',
						xtype : 'combo',   
						valueField : 'code',    //值的name属性
						mode : 'remote',  //远程数据
						displayField : "content",  //显示内容的name属性
						forceSelection : true,
						blankText : '请选择所属类型',  
						emptyText : '选择所属类型',
						editable : true,   //可以编辑
						triggerAction : 'all',
						allowBlank : false,
						hiddenName : "by1",  //作为隐藏表单传入form的值
						autoShow : true,
						selectOnFocus : true
					}, {
						fieldLabel : '出生日期',
						name : 'birthday',
						xtype : "datefield",
						format : "Y-m-d"
					}, {
						fieldLabel : '联系地址',
						name : 'address',
						xtype : 'textfield'
					}, {
						fieldLabel : '封面图片',
						name : 'uploadphoto',
						inputType : 'file'
					}]
		}]
	}, {
		xtype : 'checkboxgroup',
		fieldLabel : '兴趣爱好',
		name : 'xqah',
		columns : 4,
		items : [{
					boxLabel : 'Item 1',
					name : 'xqah',
					inputValue : '1'
				}, {
					boxLabel : 'Item 2',
					name : 'xqah',
					checked : true,  //默认选中
					inputValue : '2'
				}, {
					boxLabel : 'Item 3',
					name : 'xqah',
					inputValue : '3'
				}, {
					boxLabel : 'Item 4',
					name : 'xqah',
					inputValue : '4'
				}, {
					boxLabel : 'Item 5',
					name : 'xqah',
					inputValue : '5'
				}, {
					boxLabel : 'Item 6',
					name : 'xqah',
					inputValue : '6'
				}, {
					boxLabel : 'Item 7',
					name : 'xqah',
					inputValue : '7'
				}]
	}, {
		xtype : 'tabpanel',
		plain : true,
		bodyBorder : false,
		activeTab : 0,
		height : 200,
		defaults : {
			bodyStyle : 'padding:2px'
		},
		items : [{
					title : '备注',
					layout : 'fit',
					items : {
						xtype : 'textarea',
						name : 'remark',
						maxLength : 500
					}
				}, {
					title : '编辑推荐',
					layout : 'fit',
					items : {
						xtype : 'textarea',
						name : 'by2',
						maxLength : 500
					}
				}, {
					title : '作者简介',
					layout : 'fit',
					items : {
						xtype : 'textarea',
						name : 'by3',
						maxLength : 500
					}
				}]
	}],
	buttonAlign : "center",
	buttons : [{
				text : "保存",
				handler : function() {
					submitform();
				}
			}, {
				text : "关闭",
				handler : function() {
					window_add.hide();
				}
			}]
});
// 提交表单
function submitform() {
	if (insertform.getForm().isValid()) { // 如果验证通过
		insertform.getForm().submit({
					url : "../zdbnr.action?method=insert",
					waitMsg : '正在保存数据...',
					success : onAddSuccess,
					failure : onFailure
				});
	}
}

var onFailure = function(form, action) {
	if (action.failureType == "connect") {
		Ext.Msg.alert('服务器异常', '服务器异常,请与管理员联系!');
	} else {
		Ext.Msg.alert('错误', '您输入的用户名和密码错误!');
	}
}
// 触发事件,如:添加成功后
var onAddSuccess = function(form, action) {
	var store = grid.getStore();
	var student = new Student({
				id : action.result.stuid,
				name : form.findField('name').getValue(),
				sex : form.findField('sex').getValue(),
				birthday : form.findField('birthday').getValue(),
				by1 : form.findField('by1').getValue()
			});
	store.insert(0, [student]);
	if (store.data.length > 10) {
		store.remove(store.getAt(store.data.length - 1));
	}
	Ext.MessageBox.alert("提示", "插入成功!");
	window_add.hide();
}

var window_add = new Ext.Window({
			title : '添加',
			width : 600,
			resizable : false,
			autoHeight : true, // 自动适应高度
			modal : true,
			closeAction : 'hide',
			listeners : {
				'hide' : function() {
				}
			},
			items : [insertform]
		});
 
@RequestMapping(params = "method=selectTree")
	public ModelAndView selectTree(HttpServletRequest request,
			HttpServletResponse reponse) throws Exception {
		reponse.setContentType("text");
		reponse.setCharacterEncoding("UTF-8");
		SysDataParamContent content = new SysDataParamContent();
		content.setDataParamId(10024);
		List<SysDataParamContent> nrlist = dataZxZdbnrService
				.findByComb(content);
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		for (int i = 0; i < nrlist.size(); i++) {
			SysDataParamContent nr = nrlist.get(i);
			sb.append("{\"content\" :\"" + nr.getContent() + "\" ,\"code\" :\""
					+ nr.getCode() + "\"},");
		}
		sb.append("]");
		reponse.getWriter().write(sb.toString());
		return null;
	}


	@RequestMapping(params = "method=insert")
	public ModelAndView insert(Student stu,HttpServletRequest request, HttpServletResponse reponse)
			throws Exception {
		int count = dataZxZdbnrService.insertStudent(stu);
		reponse.setContentType("text/html"); 
		String result = "";
		if (count > 0) {
			count = studentService.findByLast();
			uploadTemplate(request,count);
			result = "{stuid:"+count+",success:true}";
		}
		reponse.getWriter().write(result);
		return null;
	}
 
var updateform = new Ext.FormPanel({
	frame : true,
	labelWidth : 70,
	bodyStyle : 'padding:5px',
	border : false,
	labelAlign : 'right',
	items : [{
		layout : 'column',
		border : false,
		items : [{
			columnWidth : .5,
			layout : 'form',
			baseCls : 'x-plain',
			border : false,
			defaults : {
				anchor : '80%'
			},
			items : [{
						name : "id",
						fieldLabel : "编号",
						xtype : "hidden"
					},{
						fieldLabel : '身份证号',
						xtype : 'textfield',
						name : 'idCard',
						maxLength : 50
					}, {
						fieldLabel : '姓名',
						xtype : 'textfield',
						name : 'name'
					}, {
						fieldLabel : '电子邮件',
						xtype : 'textfield',
						name : 'email',
						vtype : 'email'
					}, {
						xtype : 'panel',
						layout : 'table',
						fieldLabel : '性别',
						defaultType : 'radio',
						isFormField : true,
						items : [{
							name : 'sex',
							boxLabel : '<span style="color:black;font-size:12px;">男&nbsp;&nbsp;</span>',
							inputValue : '1', // 值
							checked : true
								// 默认选中
						}, {
							name : 'sex',
							boxLabel : '<span style="color:black;font-size:12px;">女</span>',
							inputValue : '2'
						}]
					}]
		}, {
			columnWidth : .5,
			layout : 'form',
			border : false,
			defaultType : 'textfield',
			defaults : {
				anchor : '80%'
			},
			items : [{
						store : ds, // 下拉列表的数据
						fieldLabel : '民族',
						name : 'by1',
						xtype : 'textfield',
						xtype : 'combo',
						valueField : 'code', // 值的name属性
						mode : 'remote', // 远程数据
						displayField : "content", // 显示内容的name属性
						forceSelection : true,
						blankText : '请选择所属类型',
						emptyText : '选择所属类型',
						editable : true, // 可以编辑
						triggerAction : 'all',
						allowBlank : false,
						hiddenName : "by1", // 作为隐藏表单传入form的值
						autoShow : true,
						selectOnFocus : true
					}, {
						fieldLabel : '出生日期',
						name : 'birthday',
						xtype : "datefield",
						format : "Y-m-d"
					}, {
						fieldLabel : '联系地址',
						name : 'address',
						xtype : 'textfield'
					}, {
						fieldLabel : '封面图片',
						name : 'uploadphoto',
						inputType : 'file'
					}]
		}]
	}, {
		xtype : 'checkboxgroup',
		fieldLabel : '兴趣爱好',
		name : 'xqah',
		columns : 4,
		items : [{
					boxLabel : 'Item 1',
					name : 'xqah',
					inputValue : '1'
				}, {
					boxLabel : 'Item 2',
					name : 'xqah',
					checked : true, // 默认选中
					inputValue : '2'
				}, {
					boxLabel : 'Item 3',
					name : 'xqah',
					inputValue : '3'
				}, {
					boxLabel : 'Item 4',
					name : 'xqah',
					inputValue : '4'
				}, {
					boxLabel : 'Item 5',
					name : 'xqah',
					inputValue : '5'
				}, {
					boxLabel : 'Item 6',
					name : 'xqah',
					inputValue : '6'
				}, {
					boxLabel : 'Item 7',
					name : 'xqah',
					inputValue : '7'
				}]
	}, {
		xtype : 'tabpanel',
		plain : true,
		bodyBorder : false,
		activeTab : 0,
		height : 200,
		defaults : {
			bodyStyle : 'padding:2px'
		},
		items : [{
					title : '备注',
					layout : 'fit',
					items : {
						xtype : 'textarea',
						name : 'remark',
						maxLength : 500
					}
				}, {
					title : '编辑推荐',
					layout : 'fit',
					items : {
						xtype : 'textarea',
						name : 'by2',
						maxLength : 500
					}
				}, {
					title : '作者简介',
					layout : 'fit',
					items : {
						xtype : 'textarea',
						name : 'by3',
						maxLength : 500
					}
				}]
	}],
	buttonAlign : "center",
	buttons : [{
				text : "修改",
				handler : function() {
					submitUpdaeForm();
				}
			}, {
				text : "关闭",
				handler : function() {
					window_edit.hide();
				}
			}]
});
// 提交表单
function submitUpdaeForm() {
	if (updateform.getForm().isValid()) { // 如果验证通过
		updateform.getForm().submit({
					url : "../student.action?method=update",
					waitMsg : '正在保存数据...',
					success : onAddSuccessUpdate,
					failure : onFailureUpdate
				});
	}
}

var onFailureUpdate = function(form, action) {
	if (action.failureType == "connect") {
		Ext.Msg.alert('服务器异常', '服务器异常,请与管理员联系!');
	} else {
		Ext.Msg.alert('错误', '您输入的用户名和密码错误!');
	}
}
var onAddSuccessUpdate = function(form, action) {
	Ext.MessageBox.alert("提示", "修改成功!");
	window_edit.hide();
}

function editloadForm(id) {
	updateform.form.load({
				waitMsg : '正在加载数据',
				waitTitle : '提示',
				url : '../student.action?method=findById',
				params : {
					id : id
				},
				method : 'GET',
				success : function(form, action) {
					// 数据加载成功.
				},
				failure : function(form, action) {
					Ext.Msg.alert('无法加载该数据');
				}
			});
}

function loadUpdateForm() {
	var stulist = grid.getSelectionModel().getSelections();
	var idList = [];
	if (stulist.length == 0) {
		Ext.Msg.alert("提示", "请选择要修改的数据!");
	} else if (stulist.length > 1) {
		Ext.Msg.alert("提示", "只能选择一条记录操作!");
	} else {
		for (var i = 0; i < stulist.length; i++) {
			idList.push(stulist[i].get('id'));
		}
		updateform.form.reset();
		updateform.isAdd = true;
		window_edit.setTitle("修改");
		window_edit.show();
		var id = idList[0];
		editloadForm(id);
	}
}

var window_edit = new Ext.Window({
			title : '修改',
			width : 600,
			resizable : false,
			autoHeight : true, // 自动适应高度
			modal : true,
			closeAction : 'hide',
			listeners : {
				'hide' : function() {
				}
			},
			items : [updateform]
		});
 
@RequestMapping(params = "method=findById")
	public ModelAndView findById(int id, HttpServletResponse response) {
		response.setContentType("text/html"); 
		response.setCharacterEncoding("UTF-8");      
		StringBuffer sb = new StringBuffer();
		Student stu = studentService.findById(id);
		sb.append("{");
		sb.append("success : true,");
		sb.append("data : {id :" + stu.getId() + ",idCard : \""
				+ stu.getIdCard() + "\",name:\"" + StringUtils.trimToEmpty(stu.getName())
				+ "\",email:\"" + StringUtils.trimToEmpty(stu.getEmail()) + "\",sex:\"" + stu.getSex()
				+ "\",by1 : \"" + StringUtils.trimToEmpty(stu.getBy1()) + "\",birthday:\""
				+ StringUtils.trimToEmpty(stu.getBirthday()) + "\",address:\"" + StringUtils.trimToEmpty(stu.getAddress())
				+ "\",xqah:\"" + StringUtils.trimToEmpty(stu.getXqah()) + "\",remark:\""
				+ StringUtils.trimToEmpty(stu.getRemark()) + "\",by2:\"" + StringUtils.trimToEmpty(stu.getBy2()) + "\",by3:\""
				+StringUtils.trimToEmpty( stu.getBy3()) + "\"}");
		sb.append("}");
		try {
			response.getWriter().write(sb.toString());
		} catch (Exception e) {
		}
		return null;
	}
	
	@RequestMapping(params = "method=update")
	public ModelAndView update(Student stu,HttpServletResponse response) {
		String result = "";
		int count = studentService.update(stu);
		if(count>0){
			result = "{message:'修改成功!',success:true}";
		}
		try {
			response.getWriter().write(result);
		} catch (Exception e) {
		}
		return null;
	}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值