require-form.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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="<%=key%>" placeholder="<%=options.keyPlaceholder||\'\'%>" size="10" /> <input type="text" name="<%=name%>[<%=index%>][value]" class="form-control" value="<%=value%>" placeholder="<%=options.valuePlaceholder||\'\'%>" /> <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. rules: {
  13. username: [/^\w{3,30}$/, __('Username must be 3 to 30 characters')],
  14. password: [/^[\S]{6,30}$/, __('Password must be 6 to 30 characters')]
  15. },
  16. validClass: 'has-success',
  17. invalidClass: 'has-error',
  18. bindClassTo: '.form-group',
  19. formClass: 'n-default n-bootstrap',
  20. msgClass: 'n-right',
  21. stopOnError: true,
  22. display: function (elem) {
  23. return $(elem).closest('.form-group').find(".control-label").text().replace(/\:/, '');
  24. },
  25. dataFilter: function (data) {
  26. if (data.code === 1) {
  27. return data.msg ? {"ok": data.msg} : '';
  28. } else {
  29. return data.msg;
  30. }
  31. },
  32. target: function (input) {
  33. var target = $(input).data("target");
  34. if (target && $(target).length > 0) {
  35. return $(target);
  36. }
  37. var $formitem = $(input).closest('.form-group'),
  38. $msgbox = $formitem.find('span.msg-box');
  39. if (!$msgbox.length) {
  40. return [];
  41. }
  42. return $msgbox;
  43. },
  44. valid: function (ret) {
  45. var that = this, submitBtn = $(".layer-footer [type=submit]", form);
  46. that.holdSubmit(true);
  47. submitBtn.addClass("disabled");
  48. //验证通过提交表单
  49. var submitResult = Form.api.submit($(ret), function (data, ret) {
  50. that.holdSubmit(false);
  51. submitBtn.removeClass("disabled");
  52. if (false === $(this).triggerHandler("success.form", [data, ret])) {
  53. return false;
  54. }
  55. if (typeof success === 'function') {
  56. if (false === success.call($(this), data, ret)) {
  57. return false;
  58. }
  59. }
  60. //提示及关闭当前窗口
  61. var msg = ret.hasOwnProperty("msg") && ret.msg !== "" ? ret.msg : __('Operation completed');
  62. parent.Toastr.success(msg);
  63. parent.$(".btn-refresh").trigger("click");
  64. var index = parent.Layer.getFrameIndex(window.name);
  65. parent.Layer.close(index);
  66. return false;
  67. }, function (data, ret) {
  68. that.holdSubmit(false);
  69. if (false === $(this).triggerHandler("error.form", [data, ret])) {
  70. return false;
  71. }
  72. submitBtn.removeClass("disabled");
  73. if (typeof error === 'function') {
  74. if (false === error.call($(this), data, ret)) {
  75. return false;
  76. }
  77. }
  78. }, submit);
  79. //如果提交失败则释放锁定
  80. if (!submitResult) {
  81. that.holdSubmit(false);
  82. submitBtn.removeClass("disabled");
  83. }
  84. return false;
  85. }
  86. }, form.data("validator-options") || {}));
  87. //移除提交按钮的disabled类
  88. $(".layer-footer [type=submit],.fixed-footer [type=submit],.normal-footer [type=submit]", form).removeClass("disabled");
  89. //自定义关闭按钮事件
  90. form.on("click", ".layer-close", function () {
  91. var index = parent.Layer.getFrameIndex(window.name);
  92. parent.Layer.close(index);
  93. return false;
  94. });
  95. },
  96. selectpicker: function (form) {
  97. //绑定select元素事件
  98. if ($(".selectpicker", form).length > 0) {
  99. require(['bootstrap-select', 'bootstrap-select-lang'], function () {
  100. $('.selectpicker', form).selectpicker();
  101. $(form).on("reset", function () {
  102. setTimeout(function () {
  103. $('.selectpicker').selectpicker('refresh').trigger("change");
  104. }, 1);
  105. });
  106. });
  107. }
  108. },
  109. selectpage: function (form) {
  110. //绑定selectpage元素事件
  111. if ($(".selectpage", form).length > 0) {
  112. require(['selectpage'], function () {
  113. $('.selectpage', form).selectPage({
  114. eAjaxSuccess: function (data) {
  115. data.list = typeof data.rows !== 'undefined' ? data.rows : (typeof data.list !== 'undefined' ? data.list : []);
  116. data.totalRow = typeof data.total !== 'undefined' ? data.total : (typeof data.totalRow !== 'undefined' ? data.totalRow : data.list.length);
  117. return data;
  118. }
  119. });
  120. });
  121. //给隐藏的元素添加上validate验证触发事件
  122. $(document).on("change", ".sp_hidden", function () {
  123. $(this).trigger("validate");
  124. });
  125. $(document).on("change", ".sp_input", function () {
  126. $(this).closest(".sp_container").find(".sp_hidden").trigger("change");
  127. });
  128. $(form).on("reset", function () {
  129. setTimeout(function () {
  130. $('.selectpage', form).selectPageClear();
  131. }, 1);
  132. });
  133. }
  134. },
  135. cxselect: function (form) {
  136. //绑定cxselect元素事件
  137. if ($("[data-toggle='cxselect']", form).length > 0) {
  138. require(['cxselect'], function () {
  139. $.cxSelect.defaults.jsonName = 'name';
  140. $.cxSelect.defaults.jsonValue = 'value';
  141. $.cxSelect.defaults.jsonSpace = 'data';
  142. $("[data-toggle='cxselect']", form).cxSelect();
  143. });
  144. }
  145. },
  146. citypicker: function (form) {
  147. //绑定城市远程插件
  148. if ($("[data-toggle='city-picker']", form).length > 0) {
  149. require(['citypicker'], function () {
  150. $(form).on("reset", function () {
  151. setTimeout(function () {
  152. $("[data-toggle='city-picker']").citypicker('refresh');
  153. }, 1);
  154. });
  155. });
  156. }
  157. },
  158. datetimepicker: function (form) {
  159. //绑定日期时间元素事件
  160. if ($(".datetimepicker", form).length > 0) {
  161. require(['bootstrap-datetimepicker'], function () {
  162. var options = {
  163. format: 'YYYY-MM-DD HH:mm:ss',
  164. icons: {
  165. time: 'fa fa-clock-o',
  166. date: 'fa fa-calendar',
  167. up: 'fa fa-chevron-up',
  168. down: 'fa fa-chevron-down',
  169. previous: 'fa fa-chevron-left',
  170. next: 'fa fa-chevron-right',
  171. today: 'fa fa-history',
  172. clear: 'fa fa-trash',
  173. close: 'fa fa-remove'
  174. },
  175. showTodayButton: true,
  176. showClose: true
  177. };
  178. $('.datetimepicker', form).parent().css('position', 'relative');
  179. $('.datetimepicker', form).datetimepicker(options).on('dp.change', function (e) {
  180. $(this, document).trigger("changed");
  181. });
  182. });
  183. }
  184. },
  185. daterangepicker: function (form) {
  186. //绑定日期时间元素事件
  187. if ($(".datetimerange", form).length > 0) {
  188. require(['bootstrap-daterangepicker'], function () {
  189. var ranges = {};
  190. ranges[__('Today')] = [Moment().startOf('day'), Moment().endOf('day')];
  191. ranges[__('Yesterday')] = [Moment().subtract(1, 'days').startOf('day'), Moment().subtract(1, 'days').endOf('day')];
  192. ranges[__('Last 7 Days')] = [Moment().subtract(6, 'days').startOf('day'), Moment().endOf('day')];
  193. ranges[__('Last 30 Days')] = [Moment().subtract(29, 'days').startOf('day'), Moment().endOf('day')];
  194. ranges[__('This Month')] = [Moment().startOf('month'), Moment().endOf('month')];
  195. ranges[__('Last Month')] = [Moment().subtract(1, 'month').startOf('month'), Moment().subtract(1, 'month').endOf('month')];
  196. var options = {
  197. timePicker: false,
  198. autoUpdateInput: false,
  199. timePickerSeconds: true,
  200. timePicker24Hour: true,
  201. autoApply: true,
  202. locale: {
  203. format: 'YYYY-MM-DD HH:mm:ss',
  204. customRangeLabel: __("Custom Range"),
  205. applyLabel: __("Apply"),
  206. cancelLabel: __("Clear"),
  207. },
  208. ranges: ranges,
  209. };
  210. var origincallback = function (start, end) {
  211. $(this.element).val(start.format(this.locale.format) + " - " + end.format(this.locale.format));
  212. $(this.element).trigger('blur');
  213. };
  214. $(".datetimerange", form).each(function () {
  215. var callback = typeof $(this).data('callback') == 'function' ? $(this).data('callback') : origincallback;
  216. $(this).on('apply.daterangepicker', function (ev, picker) {
  217. callback.call(picker, picker.startDate, picker.endDate);
  218. });
  219. $(this).on('cancel.daterangepicker', function (ev, picker) {
  220. $(this).val('').trigger('blur');
  221. });
  222. $(this).daterangepicker($.extend(true, options, $(this).data() || {}, $(this).data("daterangepicker-options") || {}));
  223. });
  224. });
  225. }
  226. },
  227. /**
  228. * 绑定上传事件
  229. * @param form
  230. * @deprecated Use faupload instead.
  231. */
  232. plupload: function (form) {
  233. Form.events.faupload(form);
  234. },
  235. /**
  236. * 绑定上传事件
  237. * @param form
  238. */
  239. faupload: function (form) {
  240. //绑定上传元素事件
  241. if ($(".plupload,.faupload", form).length > 0) {
  242. Upload.api.upload($(".plupload,.faupload", form));
  243. }
  244. },
  245. faselect: function (form) {
  246. //绑定fachoose选择附件事件
  247. if ($(".faselect,.fachoose", form).length > 0) {
  248. $(".faselect,.fachoose", form).off('click').on('click', function () {
  249. var that = this;
  250. var multiple = $(this).data("multiple") ? $(this).data("multiple") : false;
  251. var mimetype = $(this).data("mimetype") ? $(this).data("mimetype") : '';
  252. var admin_id = $(this).data("admin-id") ? $(this).data("admin-id") : '';
  253. var user_id = $(this).data("user-id") ? $(this).data("user-id") : '';
  254. mimetype = mimetype.replace(/\/\*/ig, '/');
  255. var url = $(this).data("url") ? $(this).data("url") : (typeof Backend !== 'undefined' ? "general/attachment/select" : "user/attachment");
  256. parent.Fast.api.open(url + "?element_id=" + $(this).attr("id") + "&multiple=" + multiple + "&mimetype=" + mimetype + "&admin_id=" + admin_id + "&user_id=" + user_id, __('Choose'), {
  257. callback: function (data) {
  258. var button = $("#" + $(that).attr("id"));
  259. var maxcount = $(button).data("maxcount");
  260. var input_id = $(button).data("input-id") ? $(button).data("input-id") : "";
  261. maxcount = typeof maxcount !== "undefined" ? maxcount : 0;
  262. if (input_id && data.multiple) {
  263. var urlArr = [];
  264. var inputObj = $("#" + input_id);
  265. var value = $.trim(inputObj.val());
  266. if (value !== "") {
  267. urlArr.push(inputObj.val());
  268. }
  269. var nums = value === '' ? 0 : value.split(/\,/).length;
  270. var files = data.url !== "" ? data.url.split(/\,/) : [];
  271. $.each(files, function (i, j) {
  272. var url = Config.upload.fullmode ? Fast.api.cdnurl(j) : j;
  273. urlArr.push(url);
  274. });
  275. if (maxcount > 0) {
  276. var remains = maxcount - nums;
  277. if (files.length > remains) {
  278. Toastr.error(__('You can choose up to %d file%s', remains));
  279. return false;
  280. }
  281. }
  282. var result = urlArr.join(",");
  283. inputObj.val(result).trigger("change").trigger("validate");
  284. } else {
  285. var url = Config.upload.fullmode ? Fast.api.cdnurl(data.url) : data.url;
  286. $("#" + input_id).val(url).trigger("change").trigger("validate");
  287. }
  288. }
  289. });
  290. return false;
  291. });
  292. }
  293. },
  294. fieldlist: function (form) {
  295. //绑定fieldlist
  296. if ($(".fieldlist", form).length > 0) {
  297. require(['dragsort', 'template'], function (undefined, Template) {
  298. //刷新隐藏textarea的值
  299. var refresh = function (container) {
  300. var data = {};
  301. var name = container.data("name");
  302. var textarea = $("textarea[name='" + name + "']", form);
  303. var template = container.data("template");
  304. $.each($("input,select,textarea", container).serializeArray(), function (i, j) {
  305. var reg = /\[(\w+)\]\[(\w+)\]$/g;
  306. var match = reg.exec(j.name);
  307. if (!match)
  308. return true;
  309. match[1] = "x" + parseInt(match[1]);
  310. if (typeof data[match[1]] == 'undefined') {
  311. data[match[1]] = {};
  312. }
  313. data[match[1]][match[2]] = j.value;
  314. });
  315. var result = template ? [] : {};
  316. $.each(data, function (i, j) {
  317. if (j) {
  318. if (!template) {
  319. if (j.key != '') {
  320. result[j.key] = j.value;
  321. }
  322. } else {
  323. result.push(j);
  324. }
  325. }
  326. });
  327. textarea.val(JSON.stringify(result));
  328. };
  329. //追加一行数据
  330. var append = function (container, row, initial) {
  331. var tagName = container.data("tag") || (container.is("table") ? "tr" : "dd");
  332. var index = container.data("index");
  333. var name = container.data("name");
  334. var template = container.data("template");
  335. var data = container.data();
  336. index = index ? parseInt(index) : 0;
  337. container.data("index", index + 1);
  338. row = row ? row : {};
  339. row = typeof row.key === 'undefined' || typeof row.value === 'undefined' ? {key: '', value: row} : row;
  340. var options = container.data("fieldlist-options") || {};
  341. var vars = {index: index, name: name, data: data, options: options, key: row.key, value: row.value, row: row.value};
  342. var html = template ? Template(template, vars) : Template.render(Form.config.fieldlisttpl, vars);
  343. var obj = $(html);
  344. if ((options.deleteBtn === false || options.removeBtn === false) && initial)
  345. obj.find(".btn-remove").remove();
  346. if (options.dragsortBtn === false && initial)
  347. obj.find(".btn-dragsort").remove();
  348. if ((options.readonlyKey === true || options.disableKey === true) && initial) {
  349. obj.find("input[name$='[key]']").prop("readonly", true);
  350. }
  351. obj.attr("fieldlist-item", true);
  352. obj.insertAfter($(tagName + "[fieldlist-item]", container).length > 0 ? $(tagName + "[fieldlist-item]:last", container) : $(tagName + ":first", container));
  353. if ($(".btn-append,.append", container).length > 0) {
  354. //兼容旧版本事件
  355. $(".btn-append,.append", container).trigger("fa.event.appendfieldlist", obj);
  356. } else {
  357. //新版本事件
  358. container.trigger("fa.event.appendfieldlist", obj);
  359. }
  360. return obj;
  361. };
  362. var fieldlist = $(".fieldlist", form);
  363. //监听文本框改变事件
  364. $(document).on('change keyup changed', ".fieldlist input,.fieldlist textarea,.fieldlist select", function () {
  365. var container = $(this).closest(".fieldlist");
  366. refresh(container);
  367. });
  368. //追加控制(点击按钮)
  369. fieldlist.on("click", ".btn-append,.append", function (e, row) {
  370. var container = $(this).closest(".fieldlist");
  371. append(container, row);
  372. // refresh(container);
  373. });
  374. //移除控制(点击按钮)
  375. fieldlist.on("click", ".btn-remove", function () {
  376. var container = $(this).closest(".fieldlist");
  377. var tagName = container.data("tag") || (container.is("table") ? "tr" : "dd");
  378. $(this).closest(tagName).remove();
  379. refresh(container);
  380. });
  381. //追加控制(通过事件)
  382. fieldlist.on("fa.event.appendtofieldlist", function (e, row) {
  383. var container = $(this);
  384. append(container, row);
  385. refresh(container);
  386. });
  387. //根据textarea内容重新渲染
  388. fieldlist.on("fa.event.refreshfieldlist", function () {
  389. var container = $(this);
  390. var textarea = $("textarea[name='" + container.data("name") + "']", form);
  391. //先清空已有的数据
  392. $("[fieldlist-item]", container).remove();
  393. var json = {};
  394. try {
  395. json = JSON.parse(textarea.val());
  396. } catch (e) {
  397. }
  398. $.each(json, function (i, j) {
  399. append(container, {key: i, value: j}, true);
  400. });
  401. });
  402. //拖拽排序
  403. fieldlist.each(function () {
  404. var container = $(this);
  405. var tagName = container.data("tag") || (container.is("table") ? "tr" : "dd");
  406. container.dragsort({
  407. itemSelector: tagName,
  408. dragSelector: ".btn-dragsort",
  409. dragEnd: function () {
  410. refresh(container);
  411. },
  412. placeHolderTemplate: $("<" + tagName + "/>")
  413. });
  414. if (typeof container.data("options") === 'object' && container.data("options").appendBtn === false) {
  415. $(".btn-append,.append", container).hide();
  416. }
  417. $("textarea[name='" + container.data("name") + "']", form).on("fa.event.refreshfieldlist", function () {
  418. //兼容旧版本事件
  419. $(this).closest(".fieldlist").trigger("fa.event.refreshfieldlist");
  420. });
  421. });
  422. fieldlist.trigger("fa.event.refreshfieldlist");
  423. });
  424. }
  425. },
  426. switcher: function (form) {
  427. form.on("click", "[data-toggle='switcher']", function () {
  428. if ($(this).hasClass("disabled")) {
  429. return false;
  430. }
  431. var switcher = $.proxy(function () {
  432. var input = $(this).prev("input");
  433. input = $(this).data("input-id") ? $("#" + $(this).data("input-id")) : input;
  434. if (input.length > 0) {
  435. var yes = $(this).data("yes");
  436. var no = $(this).data("no");
  437. if (input.val() == yes) {
  438. input.val(no);
  439. $("i", this).addClass("fa-flip-horizontal text-gray");
  440. } else {
  441. input.val(yes);
  442. $("i", this).removeClass("fa-flip-horizontal text-gray");
  443. }
  444. input.trigger('change');
  445. }
  446. }, this);
  447. if (typeof $(this).data("confirm") !== 'undefined') {
  448. Layer.confirm($(this).data("confirm"), function (index) {
  449. switcher();
  450. Layer.close(index);
  451. });
  452. } else {
  453. switcher();
  454. }
  455. return false;
  456. });
  457. },
  458. bindevent: function (form) {
  459. },
  460. slider: function (form) {
  461. if ($(".slider", form).length > 0) {
  462. require(['bootstrap-slider'], function () {
  463. $('.slider').removeClass('hidden').css('width', function (index, value) {
  464. return $(this).parents('.form-control').width();
  465. }).slider().on('slide', function (ev) {
  466. var data = $(this).data();
  467. if (typeof data.unit !== 'undefined') {
  468. $(this).parents('.form-control').siblings('.value').text(ev.value + data.unit);
  469. }
  470. });
  471. });
  472. }
  473. },
  474. tagsinput: function (form) {
  475. if ($("[data-role='tagsinput']", form).length > 0) {
  476. require(['tagsinput', 'autocomplete'], function () {
  477. $("[data-role='tagsinput']").tagsinput();
  478. });
  479. }
  480. },
  481. autocomplete: function (form) {
  482. if ($("[data-role='autocomplete']", form).length > 0) {
  483. require(['autocomplete'], function () {
  484. $("[data-role='autocomplete']").autocomplete();
  485. });
  486. }
  487. },
  488. favisible: function (form) {
  489. if ($("[data-favisible]", form).length == 0) {
  490. return;
  491. }
  492. var checkCondition = function (condition) {
  493. var conditionArr = condition.split(/&&/);
  494. var success = 0;
  495. var baseregex = /^([a-z0-9\_]+)([>|<|=|\!]=?)(.*)$/i, strregex = /^('|")(.*)('|")$/, regregex = /^regex:(.*)$/;
  496. // @formatter:off
  497. var operator_result = {
  498. '>': function(a, b) { return a > b; },
  499. '>=': function(a, b) { return a >= b; },
  500. '<': function(a, b) { return a < b; },
  501. '<=': function(a, b) { return a <= b; },
  502. '==': function(a, b) { return a == b; },
  503. '!=': function(a, b) { return a != b; },
  504. 'in': function(a, b) { return b.split(/\,/).indexOf(a) > -1; },
  505. 'regex': function(a, b) {
  506. var regParts = b.match(/^\/(.*?)\/([gim]*)$/);
  507. var regexp = regParts ? new RegExp(regParts[1], regParts[2]) : new RegExp(b);
  508. return regexp.test(a);
  509. }
  510. };
  511. // @formatter:on
  512. var dataArr = form.serializeArray(), dataObj = {}, fieldName, fieldValue;
  513. $(dataArr).each(function (i, field) {
  514. fieldName = field.name;
  515. fieldValue = field.value;
  516. fieldName = fieldName.substr(-2) === '[]' ? fieldName.substr(0, fieldName.length - 2) : fieldName;
  517. dataObj[fieldName] = typeof dataObj[fieldName] !== 'undefined' ? [dataObj[fieldName], fieldValue].join(',') : fieldValue;
  518. });
  519. $.each(conditionArr, function (i, item) {
  520. var basematches = baseregex.exec(item);
  521. if (basematches) {
  522. var name = basematches[1], operator = basematches[2], value = basematches[3].toString();
  523. if (operator === '=') {
  524. var strmatches = strregex.exec(value);
  525. operator = strmatches ? '==' : 'in';
  526. value = strmatches ? strmatches[2] : value;
  527. }
  528. var regmatches = regregex.exec(value);
  529. if (regmatches) {
  530. operator = 'regex';
  531. value = regmatches[1];
  532. }
  533. var chkname = "row[" + name + "]";
  534. if (typeof dataObj[chkname] === 'undefined') {
  535. return false;
  536. }
  537. var objvalue = dataObj[chkname];
  538. if ($.isArray(objvalue)) {
  539. objvalue = dataObj[chkname].join(",");
  540. }
  541. if (['>', '>=', '<', '<='].indexOf(operator) > -1) {
  542. objvalue = parseFloat(objvalue);
  543. value = parseFloat(value);
  544. }
  545. var result = operator_result[operator](objvalue, value);
  546. success += (result ? 1 : 0);
  547. }
  548. });
  549. return success === conditionArr.length;
  550. };
  551. form.on("keyup change click configchange", "input,select", function () {
  552. $("[data-favisible][data-favisible!='']", form).each(function () {
  553. var visible = $(this).data("favisible");
  554. var groupArr = visible.split(/\|\|/);
  555. var success = 0;
  556. $.each(groupArr, function (i, j) {
  557. if (checkCondition(j)) {
  558. success++;
  559. }
  560. });
  561. if (success > 0) {
  562. $(this).removeClass("hidden");
  563. } else {
  564. $(this).addClass("hidden");
  565. }
  566. });
  567. });
  568. //追加上忽略元素
  569. setTimeout(function () {
  570. form.data('validator').options.ignore += ((form.data('validator').options.ignore ? ',' : '') + '[data-favisible] :hidden,[data-favisible]:hidden');
  571. }, 0);
  572. $("input,select", form).trigger("configchange");
  573. }
  574. },
  575. api: {
  576. submit: function (form, success, error, submit) {
  577. if (form.length === 0) {
  578. Toastr.error("表单未初始化完成,无法提交");
  579. return false;
  580. }
  581. if (typeof submit === 'function') {
  582. if (false === submit.call(form, success, error)) {
  583. return false;
  584. }
  585. }
  586. var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
  587. type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
  588. url = form.attr("action");
  589. url = url ? url : location.href;
  590. //修复当存在多选项元素时提交的BUG
  591. var params = {};
  592. var multipleList = $("[name$='[]']", form);
  593. if (multipleList.length > 0) {
  594. var postFields = form.serializeArray().map(function (obj) {
  595. return $(obj).prop("name");
  596. });
  597. $.each(multipleList, function (i, j) {
  598. if (postFields.indexOf($(this).prop("name")) < 0) {
  599. params[$(this).prop("name")] = '';
  600. }
  601. });
  602. }
  603. //调用Ajax请求方法
  604. Fast.api.ajax({
  605. type: type,
  606. url: url,
  607. data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : ''),
  608. dataType: 'json',
  609. complete: function (xhr) {
  610. var token = xhr.getResponseHeader('__token__');
  611. if (token) {
  612. $("input[name='__token__']").val(token);
  613. }
  614. }
  615. }, function (data, ret) {
  616. $('.form-group', form).removeClass('has-feedback has-success has-error');
  617. if (data && typeof data === 'object') {
  618. //刷新客户端token
  619. if (typeof data.token !== 'undefined') {
  620. $("input[name='__token__']").val(data.token);
  621. }
  622. //调用客户端事件
  623. if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
  624. data.callback.call(form, data);
  625. }
  626. }
  627. if (typeof success === 'function') {
  628. if (false === success.call(form, data, ret)) {
  629. return false;
  630. }
  631. }
  632. }, function (data, ret) {
  633. if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
  634. $("input[name='__token__']").val(data.token);
  635. }
  636. if (typeof error === 'function') {
  637. if (false === error.call(form, data, ret)) {
  638. return false;
  639. }
  640. }
  641. });
  642. return true;
  643. },
  644. bindevent: function (form, success, error, submit) {
  645. form = typeof form === 'object' ? form : $(form);
  646. var events = Form.events;
  647. events.bindevent(form);
  648. events.validator(form, success, error, submit);
  649. events.selectpicker(form);
  650. events.daterangepicker(form);
  651. events.selectpage(form);
  652. events.cxselect(form);
  653. events.citypicker(form);
  654. events.datetimepicker(form);
  655. events.faupload(form);
  656. events.faselect(form);
  657. events.fieldlist(form);
  658. events.slider(form);
  659. events.switcher(form);
  660. events.tagsinput(form);
  661. events.autocomplete(form);
  662. events.favisible(form);
  663. },
  664. custom: {}
  665. },
  666. };
  667. return Form;
  668. });