require-form.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. define(['jquery', 'bootstrap', 'upload', 'validator', 'validator-lang'], function ($, undefined, Upload, Validator, undefined) {
  2. var Form = {
  3. config: {
  4. fieldlisttpl: '<dd class="form-inline"><input type="text" name="<%=name%>[<%=index%>][key]" class="form-control" value="<%=row.key%>" size="10" /> <input type="text" name="<%=name%>[<%=index%>][value]" class="form-control" value="<%=row.value%>" /> <span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span> <span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span></dd>'
  5. },
  6. events: {
  7. validator: function (form, success, error, submit) {
  8. if (!form.is("form"))
  9. return;
  10. //绑定表单事件
  11. form.validator($.extend({
  12. validClass: 'has-success',
  13. invalidClass: 'has-error',
  14. bindClassTo: '.form-group',
  15. formClass: 'n-default n-bootstrap',
  16. msgClass: 'n-right',
  17. stopOnError: true,
  18. display: function (elem) {
  19. return $(elem).closest('.form-group').find(".control-label").text().replace(/\:/, '');
  20. },
  21. dataFilter: function (data) {
  22. if (data.code === 1) {
  23. return data.msg ? {"ok": data.msg} : '';
  24. } else {
  25. return data.msg;
  26. }
  27. },
  28. target: function (input) {
  29. var target = $(input).data("target");
  30. if (target && $(target).size() > 0) {
  31. return $(target);
  32. }
  33. var $formitem = $(input).closest('.form-group'),
  34. $msgbox = $formitem.find('span.msg-box');
  35. if (!$msgbox.length) {
  36. return [];
  37. }
  38. return $msgbox;
  39. },
  40. valid: function (ret) {
  41. var that = this, submitBtn = $(".layer-footer [type=submit]", form);
  42. that.holdSubmit(true);
  43. submitBtn.addClass("disabled");
  44. //验证通过提交表单
  45. var submitResult = Form.api.submit($(ret), function (data, ret) {
  46. that.holdSubmit(false);
  47. submitBtn.removeClass("disabled");
  48. if (false === $(this).triggerHandler("success.form", [data, ret])) {
  49. return false;
  50. }
  51. if (typeof success === 'function') {
  52. if (false === success.call($(this), data, ret)) {
  53. return false;
  54. }
  55. }
  56. //提示及关闭当前窗口
  57. var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
  58. parent.Toastr.success(msg);
  59. parent.$(".btn-refresh").trigger("click");
  60. var index = parent.Layer.getFrameIndex(window.name);
  61. parent.Layer.close(index);
  62. return false;
  63. }, function (data, ret) {
  64. that.holdSubmit(false);
  65. if (false === $(this).triggerHandler("error.form", [data, ret])) {
  66. return false;
  67. }
  68. submitBtn.removeClass("disabled");
  69. if (typeof error === 'function') {
  70. if (false === error.call($(this), data, ret)) {
  71. return false;
  72. }
  73. }
  74. }, submit);
  75. //如果提交失败则释放锁定
  76. if (!submitResult) {
  77. that.holdSubmit(false);
  78. submitBtn.removeClass("disabled");
  79. }
  80. return false;
  81. }
  82. }, form.data("validator-options") || {}));
  83. //移除提交按钮的disabled类
  84. $(".layer-footer [type=submit],.fixed-footer [type=submit],.normal-footer [type=submit]", form).removeClass("disabled");
  85. //自定义关闭按钮事件
  86. form.on("click", ".layer-close", function () {
  87. var index = parent.Layer.getFrameIndex(window.name);
  88. parent.Layer.close(index);
  89. return false;
  90. });
  91. },
  92. selectpicker: function (form) {
  93. //绑定select元素事件
  94. if ($(".selectpicker", form).size() > 0) {
  95. require(['bootstrap-select', 'bootstrap-select-lang'], function () {
  96. $('.selectpicker', form).selectpicker();
  97. $(form).on("reset", function () {
  98. setTimeout(function () {
  99. $('.selectpicker').selectpicker('refresh').trigger("change");
  100. }, 1);
  101. });
  102. });
  103. }
  104. },
  105. selectpage: function (form) {
  106. //绑定selectpage元素事件
  107. if ($(".selectpage", form).size() > 0) {
  108. require(['selectpage'], function () {
  109. $('.selectpage', form).selectPage({
  110. eAjaxSuccess: function (data) {
  111. data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
  112. data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
  113. return data;
  114. }
  115. });
  116. });
  117. //给隐藏的元素添加上validate验证触发事件
  118. $(document).on("change", ".sp_hidden", function () {
  119. $(this).trigger("validate");
  120. });
  121. $(document).on("change", ".sp_input", function () {
  122. $(this).closest(".sp_container").find(".sp_hidden").trigger("change");
  123. });
  124. $(form).on("reset", function () {
  125. setTimeout(function () {
  126. $('.selectpage', form).selectPageClear();
  127. }, 1);
  128. });
  129. }
  130. },
  131. cxselect: function (form) {
  132. //绑定cxselect元素事件
  133. if ($("[data-toggle='cxselect']", form).size() > 0) {
  134. require(['cxselect'], function () {
  135. $.cxSelect.defaults.jsonName = 'name';
  136. $.cxSelect.defaults.jsonValue = 'value';
  137. $.cxSelect.defaults.jsonSpace = 'data';
  138. $("[data-toggle='cxselect']", form).cxSelect();
  139. });
  140. }
  141. },
  142. citypicker: function (form) {
  143. //绑定城市远程插件
  144. if ($("[data-toggle='city-picker']", form).size() > 0) {
  145. require(['citypicker'], function () {
  146. $(form).on("reset", function () {
  147. setTimeout(function () {
  148. $("[data-toggle='city-picker']").citypicker('refresh');
  149. }, 1);
  150. });
  151. });
  152. }
  153. },
  154. datetimepicker: function (form) {
  155. //绑定日期时间元素事件
  156. if ($(".datetimepicker", form).size() > 0) {
  157. require(['bootstrap-datetimepicker'], function () {
  158. var options = {
  159. format: 'YYYY-MM-DD HH:mm:ss',
  160. icons: {
  161. time: 'fa fa-clock-o',
  162. date: 'fa fa-calendar',
  163. up: 'fa fa-chevron-up',
  164. down: 'fa fa-chevron-down',
  165. previous: 'fa fa-chevron-left',
  166. next: 'fa fa-chevron-right',
  167. today: 'fa fa-history',
  168. clear: 'fa fa-trash',
  169. close: 'fa fa-remove'
  170. },
  171. showTodayButton: true,
  172. showClose: true
  173. };
  174. $('.datetimepicker', form).parent().css('position', 'relative');
  175. $('.datetimepicker', form).datetimepicker(options).on('dp.change', function (e) {
  176. $(this, document).trigger("changed");
  177. });
  178. });
  179. }
  180. },
  181. daterangepicker: function (form) {
  182. //绑定日期时间元素事件
  183. if ($(".datetimerange", form).size() > 0) {
  184. require(['bootstrap-daterangepicker'], function () {
  185. var ranges = {};
  186. ranges[__('Today')] = [Moment().startOf('day'), Moment().endOf('day')];
  187. ranges[__('Yesterday')] = [Moment().subtract(1, 'days').startOf('day'), Moment().subtract(1, 'days').endOf('day')];
  188. ranges[__('Last 7 Days')] = [Moment().subtract(6, 'days').startOf('day'), Moment().endOf('day')];
  189. ranges[__('Last 30 Days')] = [Moment().subtract(29, 'days').startOf('day'), Moment().endOf('day')];
  190. ranges[__('This Month')] = [Moment().startOf('month'), Moment().endOf('month')];
  191. ranges[__('Last Month')] = [Moment().subtract(1, 'month').startOf('month'), Moment().subtract(1, 'month').endOf('month')];
  192. var options = {
  193. timePicker: false,
  194. autoUpdateInput: false,
  195. timePickerSeconds: true,
  196. timePicker24Hour: true,
  197. autoApply: true,
  198. locale: {
  199. format: 'YYYY-MM-DD HH:mm:ss',
  200. customRangeLabel: __("Custom Range"),
  201. applyLabel: __("Apply"),
  202. cancelLabel: __("Clear"),
  203. },
  204. ranges: ranges,
  205. };
  206. var origincallback = function (start, end) {
  207. $(this.element).val(start.format(this.locale.format) + " - " + end.format(this.locale.format));
  208. $(this.element).trigger('blur');
  209. };
  210. $(".datetimerange", form).each(function () {
  211. var callback = typeof $(this).data('callback') == 'function' ? $(this).data('callback') : origincallback;
  212. $(this).on('apply.daterangepicker', function (ev, picker) {
  213. callback.call(picker, picker.startDate, picker.endDate);
  214. });
  215. $(this).on('cancel.daterangepicker', function (ev, picker) {
  216. $(this).val('').trigger('blur');
  217. });
  218. $(this).daterangepicker($.extend(true, options, $(this).data()), callback);
  219. });
  220. });
  221. }
  222. },
  223. /**
  224. * 绑定上传事件
  225. * @param form
  226. * @deprecated Use faupload instead.
  227. */
  228. plupload: function (form) {
  229. Form.events.faupload(form);
  230. },
  231. /**
  232. * 绑定上传事件
  233. * @param form
  234. */
  235. faupload: function (form) {
  236. //绑定上传元素事件
  237. if ($(".plupload,.faupload", form).size() > 0) {
  238. Upload.api.upload($(".plupload,.faupload", form));
  239. }
  240. },
  241. faselect: function (form) {
  242. //绑定fachoose选择附件事件
  243. if ($(".faselect,.fachoose", form).size() > 0) {
  244. $(".faselect,.fachoose", form).on('click', function () {
  245. var that = this;
  246. var multiple = $(this).data("multiple") ? $(this).data("multiple") : false;
  247. var mimetype = $(this).data("mimetype") ? $(this).data("mimetype") : '';
  248. var admin_id = $(this).data("admin-id") ? $(this).data("admin-id") : '';
  249. var user_id = $(this).data("user-id") ? $(this).data("user-id") : '';
  250. var url = $(this).data("url") ? $(this).data("url") : (typeof Backend !== 'undefined' ? "general/attachment/select" : "user/attachment");
  251. parent.Fast.api.open(url + "?element_id=" + $(this).attr("id") + "&multiple=" + multiple + "&mimetype=" + mimetype + "&admin_id=" + admin_id + "&user_id=" + user_id, __('Choose'), {
  252. callback: function (data) {
  253. var button = $("#" + $(that).attr("id"));
  254. var maxcount = $(button).data("maxcount");
  255. var input_id = $(button).data("input-id") ? $(button).data("input-id") : "";
  256. maxcount = typeof maxcount !== "undefined" ? maxcount : 0;
  257. if (input_id && data.multiple) {
  258. var urlArr = [];
  259. var inputObj = $("#" + input_id);
  260. var value = $.trim(inputObj.val());
  261. if (value !== "") {
  262. urlArr.push(inputObj.val());
  263. }
  264. urlArr.push(data.url)
  265. var result = urlArr.join(",");
  266. if (maxcount > 0) {
  267. var nums = value === '' ? 0 : value.split(/\,/).length;
  268. var files = data.url !== "" ? data.url.split(/\,/) : [];
  269. var remains = maxcount - nums;
  270. if (files.length > remains) {
  271. Toastr.error(__('You can choose up to %d file%s', remains));
  272. return false;
  273. }
  274. }
  275. inputObj.val(result).trigger("change").trigger("validate");
  276. } else {
  277. $("#" + input_id).val(data.url).trigger("change").trigger("validate");
  278. }
  279. }
  280. });
  281. return false;
  282. });
  283. }
  284. },
  285. fieldlist: function (form) {
  286. //绑定fieldlist
  287. if ($(".fieldlist", form).size() > 0) {
  288. require(['dragsort', 'template'], function (undefined, Template) {
  289. //刷新隐藏textarea的值
  290. var refresh = function (name) {
  291. var data = {};
  292. var textarea = $("textarea[name='" + name + "']", form);
  293. var container = $(".fieldlist[data-name='" + name + "']");
  294. var template = container.data("template");
  295. $.each($("input,select,textarea", container).serializeArray(), function (i, j) {
  296. var reg = /\[(\w+)\]\[(\w+)\]$/g;
  297. var match = reg.exec(j.name);
  298. if (!match)
  299. return true;
  300. match[1] = "x" + parseInt(match[1]);
  301. if (typeof data[match[1]] == 'undefined') {
  302. data[match[1]] = {};
  303. }
  304. data[match[1]][match[2]] = j.value;
  305. });
  306. var result = template ? [] : {};
  307. $.each(data, function (i, j) {
  308. if (j) {
  309. if (!template) {
  310. if (j.key != '') {
  311. result[j.key] = j.value;
  312. }
  313. } else {
  314. result.push(j);
  315. }
  316. }
  317. });
  318. textarea.val(JSON.stringify(result));
  319. };
  320. //监听文本框改变事件
  321. $(document).on('change keyup changed', ".fieldlist input,.fieldlist textarea,.fieldlist select", function () {
  322. refresh($(this).closest(".fieldlist").data("name"));
  323. });
  324. //追加控制
  325. $(".fieldlist", form).on("click", ".btn-append,.append", function (e, row) {
  326. var container = $(this).closest(".fieldlist");
  327. var tagName = container.data("tag") || "dd";
  328. var index = container.data("index");
  329. var name = container.data("name");
  330. var template = container.data("template");
  331. var data = container.data();
  332. index = index ? parseInt(index) : 0;
  333. container.data("index", index + 1);
  334. row = row ? row : {};
  335. var vars = {index: index, name: name, data: data, row: row};
  336. var html = template ? Template(template, vars) : Template.render(Form.config.fieldlisttpl, vars);
  337. $(html).insertBefore($(tagName + ":last", container));
  338. $(this).trigger("fa.event.appendfieldlist", $(this).closest(tagName).prev());
  339. });
  340. //移除控制
  341. $(".fieldlist", form).on("click", ".btn-remove", function () {
  342. var container = $(this).closest(".fieldlist");
  343. var tagName = container.data("tag") || "dd";
  344. $(this).closest(tagName).remove();
  345. refresh(container.data("name"));
  346. });
  347. //渲染数据&拖拽排序
  348. $(".fieldlist", form).each(function () {
  349. var container = this;
  350. var tagName = $(this).data("tag") || "dd";
  351. $(this).dragsort({
  352. itemSelector: tagName,
  353. dragSelector: ".btn-dragsort",
  354. dragEnd: function () {
  355. refresh($(this).closest(".fieldlist").data("name"));
  356. },
  357. placeHolderTemplate: $("<" + tagName + "/>")
  358. });
  359. var textarea = $("textarea[name='" + $(this).data("name") + "']", form);
  360. if (textarea.val() == '') {
  361. return true;
  362. }
  363. var template = $(this).data("template");
  364. var json = {};
  365. try {
  366. json = JSON.parse(textarea.val());
  367. } catch (e) {
  368. }
  369. $.each(json, function (i, j) {
  370. $(".btn-append,.append", container).trigger('click', template ? j : {
  371. key: i,
  372. value: j
  373. });
  374. });
  375. });
  376. });
  377. }
  378. },
  379. switcher: function (form) {
  380. form.on("click", "[data-toggle='switcher']", function () {
  381. if ($(this).hasClass("disabled")) {
  382. return false;
  383. }
  384. var switcher = $.proxy(function () {
  385. var input = $(this).prev("input");
  386. input = $(this).data("input-id") ? $("#" + $(this).data("input-id")) : input;
  387. if (input.size() > 0) {
  388. var yes = $(this).data("yes");
  389. var no = $(this).data("no");
  390. if (input.val() == yes) {
  391. input.val(no);
  392. $("i", this).addClass("fa-flip-horizontal text-gray");
  393. } else {
  394. input.val(yes);
  395. $("i", this).removeClass("fa-flip-horizontal text-gray");
  396. }
  397. input.trigger('change');
  398. }
  399. }, this);
  400. if (typeof $(this).data("confirm") !== 'undefined') {
  401. Layer.confirm($(this).data("confirm"), function (index) {
  402. switcher();
  403. Layer.close(index);
  404. });
  405. } else {
  406. switcher();
  407. }
  408. return false;
  409. });
  410. },
  411. bindevent: function (form) {
  412. },
  413. slider: function (form) {
  414. if ($(".slider", form).size() > 0) {
  415. require(['bootstrap-slider'], function () {
  416. $('.slider').removeClass('hidden').css('width', function (index, value) {
  417. return $(this).parents('.form-control').width();
  418. }).slider().on('slide', function (ev) {
  419. var data = $(this).data();
  420. if (typeof data.unit !== 'undefined') {
  421. $(this).parents('.form-control').siblings('.value').text(ev.value + data.unit);
  422. }
  423. });
  424. });
  425. }
  426. }
  427. },
  428. api: {
  429. submit: function (form, success, error, submit) {
  430. if (form.size() === 0) {
  431. Toastr.error("表单未初始化完成,无法提交");
  432. return false;
  433. }
  434. if (typeof submit === 'function') {
  435. if (false === submit.call(form, success, error)) {
  436. return false;
  437. }
  438. }
  439. var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
  440. type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
  441. url = form.attr("action");
  442. url = url ? url : location.href;
  443. //修复当存在多选项元素时提交的BUG
  444. var params = {};
  445. var multipleList = $("[name$='[]']", form);
  446. if (multipleList.size() > 0) {
  447. var postFields = form.serializeArray().map(function (obj) {
  448. return $(obj).prop("name");
  449. });
  450. $.each(multipleList, function (i, j) {
  451. if (postFields.indexOf($(this).prop("name")) < 0) {
  452. params[$(this).prop("name")] = '';
  453. }
  454. });
  455. }
  456. //调用Ajax请求方法
  457. Fast.api.ajax({
  458. type: type,
  459. url: url,
  460. data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : ''),
  461. dataType: 'json',
  462. complete: function (xhr) {
  463. var token = xhr.getResponseHeader('__token__');
  464. if (token) {
  465. $("input[name='__token__']").val(token);
  466. }
  467. }
  468. }, function (data, ret) {
  469. $('.form-group', form).removeClass('has-feedback has-success has-error');
  470. if (data && typeof data === 'object') {
  471. //刷新客户端token
  472. if (typeof data.token !== 'undefined') {
  473. $("input[name='__token__']").val(data.token);
  474. }
  475. //调用客户端事件
  476. if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
  477. data.callback.call(form, data);
  478. }
  479. }
  480. if (typeof success === 'function') {
  481. if (false === success.call(form, data, ret)) {
  482. return false;
  483. }
  484. }
  485. }, function (data, ret) {
  486. if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
  487. $("input[name='__token__']").val(data.token);
  488. }
  489. if (typeof error === 'function') {
  490. if (false === error.call(form, data, ret)) {
  491. return false;
  492. }
  493. }
  494. });
  495. return true;
  496. },
  497. bindevent: function (form, success, error, submit) {
  498. form = typeof form === 'object' ? form : $(form);
  499. var events = Form.events;
  500. events.bindevent(form);
  501. events.validator(form, success, error, submit);
  502. events.selectpicker(form);
  503. events.daterangepicker(form);
  504. events.selectpage(form);
  505. events.cxselect(form);
  506. events.citypicker(form);
  507. events.datetimepicker(form);
  508. events.faupload(form);
  509. events.faselect(form);
  510. events.fieldlist(form);
  511. events.slider(form);
  512. events.switcher(form);
  513. },
  514. custom: {}
  515. },
  516. };
  517. return Form;
  518. });