You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

506 lines
26 KiB

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