require-form.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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).off('click').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") || (container.is("table") ? "tr" : "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).attr("fieldlist-item", true).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") || (container.is("table") ? "tr" : "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") || ($(this).is("table") ? "tr" : "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. textarea.on("fa.event.refreshfieldlist", function () {
  365. $("[fieldlist-item]", container).remove();
  366. var json = {};
  367. try {
  368. json = JSON.parse($(this).val());
  369. } catch (e) {
  370. }
  371. $.each(json, function (i, j) {
  372. $(".btn-append,.append", container).trigger('click', template ? j : {
  373. key: i, value: j
  374. });
  375. });
  376. });
  377. textarea.trigger("fa.event.refreshfieldlist");
  378. });
  379. });
  380. }
  381. },
  382. switcher: function (form) {
  383. form.on("click", "[data-toggle='switcher']", function () {
  384. if ($(this).hasClass("disabled")) {
  385. return false;
  386. }
  387. var switcher = $.proxy(function () {
  388. var input = $(this).prev("input");
  389. input = $(this).data("input-id") ? $("#" + $(this).data("input-id")) : input;
  390. if (input.size() > 0) {
  391. var yes = $(this).data("yes");
  392. var no = $(this).data("no");
  393. if (input.val() == yes) {
  394. input.val(no);
  395. $("i", this).addClass("fa-flip-horizontal text-gray");
  396. } else {
  397. input.val(yes);
  398. $("i", this).removeClass("fa-flip-horizontal text-gray");
  399. }
  400. input.trigger('change');
  401. }
  402. }, this);
  403. if (typeof $(this).data("confirm") !== 'undefined') {
  404. Layer.confirm($(this).data("confirm"), function (index) {
  405. switcher();
  406. Layer.close(index);
  407. });
  408. } else {
  409. switcher();
  410. }
  411. return false;
  412. });
  413. },
  414. bindevent: function (form) {
  415. },
  416. slider: function (form) {
  417. if ($(".slider", form).size() > 0) {
  418. require(['bootstrap-slider'], function () {
  419. $('.slider').removeClass('hidden').css('width', function (index, value) {
  420. return $(this).parents('.form-control').width();
  421. }).slider().on('slide', function (ev) {
  422. var data = $(this).data();
  423. if (typeof data.unit !== 'undefined') {
  424. $(this).parents('.form-control').siblings('.value').text(ev.value + data.unit);
  425. }
  426. });
  427. });
  428. }
  429. }
  430. },
  431. api: {
  432. submit: function (form, success, error, submit) {
  433. if (form.size() === 0) {
  434. Toastr.error("表单未初始化完成,无法提交");
  435. return false;
  436. }
  437. if (typeof submit === 'function') {
  438. if (false === submit.call(form, success, error)) {
  439. return false;
  440. }
  441. }
  442. var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
  443. type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
  444. url = form.attr("action");
  445. url = url ? url : location.href;
  446. //修复当存在多选项元素时提交的BUG
  447. var params = {};
  448. var multipleList = $("[name$='[]']", form);
  449. if (multipleList.size() > 0) {
  450. var postFields = form.serializeArray().map(function (obj) {
  451. return $(obj).prop("name");
  452. });
  453. $.each(multipleList, function (i, j) {
  454. if (postFields.indexOf($(this).prop("name")) < 0) {
  455. params[$(this).prop("name")] = '';
  456. }
  457. });
  458. }
  459. //调用Ajax请求方法
  460. Fast.api.ajax({
  461. type: type,
  462. url: url,
  463. data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : ''),
  464. dataType: 'json',
  465. complete: function (xhr) {
  466. var token = xhr.getResponseHeader('__token__');
  467. if (token) {
  468. $("input[name='__token__']").val(token);
  469. }
  470. }
  471. }, function (data, ret) {
  472. $('.form-group', form).removeClass('has-feedback has-success has-error');
  473. if (data && typeof data === 'object') {
  474. //刷新客户端token
  475. if (typeof data.token !== 'undefined') {
  476. $("input[name='__token__']").val(data.token);
  477. }
  478. //调用客户端事件
  479. if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
  480. data.callback.call(form, data);
  481. }
  482. }
  483. if (typeof success === 'function') {
  484. if (false === success.call(form, data, ret)) {
  485. return false;
  486. }
  487. }
  488. }, function (data, ret) {
  489. if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
  490. $("input[name='__token__']").val(data.token);
  491. }
  492. if (typeof error === 'function') {
  493. if (false === error.call(form, data, ret)) {
  494. return false;
  495. }
  496. }
  497. });
  498. return true;
  499. },
  500. bindevent: function (form, success, error, submit) {
  501. form = typeof form === 'object' ? form : $(form);
  502. var events = Form.events;
  503. events.bindevent(form);
  504. events.validator(form, success, error, submit);
  505. events.selectpicker(form);
  506. events.daterangepicker(form);
  507. events.selectpage(form);
  508. events.cxselect(form);
  509. events.citypicker(form);
  510. events.datetimepicker(form);
  511. events.faupload(form);
  512. events.faselect(form);
  513. events.fieldlist(form);
  514. events.slider(form);
  515. events.switcher(form);
  516. },
  517. custom: {}
  518. },
  519. };
  520. return Form;
  521. });