require-form.js 29 KB

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