第 12 戰攻克商品管理模塊的添加與更新功能,相比分類管理增加了圖片上傳、富文本描述、分類下拉聯動、價格數字框等復雜交互。本文深度解析 EasyUI 表單驗證擴展、Combobox 遠程加載、Form 數據回顯、Ajax 提交流程的最佳實踐。
enctype="multipart/form-data" 支持文件上傳$.extend($.fn.validatebox.defaults.rules, {
format: {
validator: function(value, param) {
var ext = value.substring(value.lastIndexOf('.') + 1).toLowerCase();
return param[0].split(",").includes(ext);
},
message: '文件後綴必須為: {0}'
}
});
// 分類下拉框遠程加載
$("#cc").combobox({
url: 'category_query.action',
valueField: 'id', textField: 'type',
panelHeight: 'auto', width: 120,
required: true, missingMessage: '請選擇所屬分類'
});
// 價格數字框:兩位小數、$ 前綴
$("input[name=price]").numberbox({
required: true, min: 0, precision: 2, prefix: '$'
});
// 圖片驗證綁定自定義規則
$("input[name='fileImage.upload']").validatebox({
required: true, validType: "format['gif,jpg,jpeg,png']"
});
// 文本域驗證
$("textarea[name=remark], textarea[name=xremark]").validatebox({
required: true, missingMessage: '請輸入商品描述'
});
$("#ff").form("disableValidation"); // 初始禁用
$("#submit").click(function() {
$("#ff").form("enableValidation");
if ($("#ff").form("validate")) {
$("#ff").form('submit', {
url: 'product_save.action',
success: function() {
parent.$("#win").window("close");
parent.$("iframe[title='商品管理']").get(0).contentWindow.$("#dg").datagrid("reload");
}
});
}
});
關鍵點:disableValidation 避免頁面載入即報錯,enableValidation 按需啟用,成功後關閉彈窗並刷新父頁面 DataGrid。
var rows = dg.datagrid("getSelections");
$("#ff").form('load', {
id: rows[0].id,
name: rows[0].name,
price: rows[0].price,
remark: rows[0].remark,
xremark: rows[0].xremark,
commend: rows[0].commend,
open: rows[0].open,
'category.id': rows[0].category.id // 易不支持點語法,需引號
});
更新頁同樣要求上傳圖片(required: true),實際業務中可改為非必填,保留原圖邏輯由後端控制。
url: 'product_update.action' // 對應 Action update 方法
public void save() throws Exception {
String pic = fileUpload.uploadFile(fileImage); // 組件化上傳
model.setPic(pic);
model.setDate(new Date()); // 前端不傳日期,後端補齊
productService.save(model);
}
public void update() throws Exception {
String pic = fileUpload.uploadFile(fileImage);
model.setPic(pic);
model.setDate(new Date());
productService.update(model);
}
文件上傳邏輯完全委託 FileUpload 組件,Action 僅負責業務字段組裝與持久化調用。
| 場景 | 組件 | 關鍵配置 |
|---|---|---|
| 必填文本 | validatebox | required: true, missingMessage |
| 數字/金額 | numberbox | precision: 2, prefix: '$', min: 0 |
| 下拉選擇 | combobox | url, valueField, textField, required |
| 文件格式 | validatebox + 自定義規則 | validType: "format['ext1,ext2']" |
| 富文本 | validatebox (textarea) | required: true |
enctype="multipart/form-data" 否則文件上傳失效combobox 寬度需同時設置 width 和 panelWidthcategory.id)需用引號 'category.id'datagrid("reload") 而非 load,保持分頁狀態商品管理模塊至此 CRUD 完全閉環,為前台購物、後台報表提供穩固數據基座。