require-form.js 38 KB

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