使用 Ext.js 进行添加或编辑操作时的唯一性校验

 

最近在维护一个老项目时,使用 Ext.js 做字典表的增删改查操作时犯了难:

添加字典某一项时要校验唯一性,对它进行编辑时如果值不变就不用发起校验,如果值改变也要校验唯一性。因为根本没用过这个框架,找了好久才解决这个问题,这里记录一下:

 

1.首先定义几个全局变量:

        // 编辑字典时:未修改时pddId的值
	var editPddId;
	// 编辑字典时:未修改时statusKey的值
        var editStatusKeyOld;
	// 控件是否可用
	var isEnable = true;

 

2.在添加/编辑方法中为项值文本框添加校验:

	new Ext.form.TextField({
	    fieldLabel: '项值*',
	    name: 'statusKey',
	    id: 'statusKey',
	    readOnly: false,
	    allowBlank: false,
	    validationEvent : 'change',
		validator: function(editStatusKeyNew) {
			// 如果项值没有改变就不校验唯一性
			if(editStatusKeyOld == editStatusKeyNew){
				return true;
			}
			
			// 只能添加pddId为300的子级项值(由于需求不同,我这里做了限定:只能添加该类型的子项,
                        // 如果不需要可以去掉该判断)
			if(editPddId == undefined) {
				editPddId = 300;
			}
			
			if (editStatusKeyNew != '' || editStatusKeyOld == undefined) {
				Ext.Ajax.request({
					url : './isExistStatusKey',
					method : 'post',
					params : { pddId: editPddId, statusKey: Ext.getCmp('statusKey').getValue() },
					success : function(response, options) {
						if (response.responseText == '1') {
							isEnable = false;
							Ext.getCmp('statusKey').markInvalid('该项值已经存在');
						} else {
							isEnable = true;
	                        Ext.getCmp('statusKey').clearInvalid();
						}
					}
				});
			}
			return isEnable;
		}
	})

 

3.后台校验方法:

        /**
	 * 	判断项值是否存在
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/isExistStatusKey", method = RequestMethod.POST)
	public void isExistStatusKey(HttpServletRequest request,
			HttpServletResponse response) {

		response.setCharacterEncoding("UTF-8");
		String pddId = request.getParameter("pddId");
		String statusKey = request.getParameter("statusKey");
		int result = dataDictionaryDAOImpl.checkStatusKey(pddId, statusKey);

		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(result);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

 

4.DAOImpl 实现类:

        /**
	 * 校验项值是否存在
	 * @param statusKey	项值
	 * @return 1:存在;2:不存在
	 */
	public int checkStatusKey(String pddId, String statusKey) {
		int exsit = 0;
		String sql = "select ddId from data_dictionary_tbl " + 
                    "where pddId = '"+ pddId +"' and status_key = '"
				+ statusKey + "'";
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection conn =JDBCUtil.getConnection();
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				exsit = 1;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(ps, rs, conn);
		}
		return exsit;
	}

 

最后附上效果图:

添加:

使用 Ext.js 进行添加或编辑操作时的唯一性校验_第1张图片

 

编辑:

使用 Ext.js 进行添加或编辑操作时的唯一性校验_第2张图片

OK!

你可能感兴趣的:(使用 Ext.js 进行添加或编辑操作时的唯一性校验)