Form.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. import '../jquery-form/jquery.form.min';
  2. let formCallbacks = {
  3. before: [], success: [], error: []
  4. };
  5. class Form {
  6. constructor(options) {
  7. let _this = this;
  8. _this.options = $.extend({
  9. // 表单的 jquery 对象或者css选择器
  10. form: null,
  11. // 开启表单验证
  12. validate: false,
  13. // 确认弹窗
  14. confirm: {title: null, content: null},
  15. // 表单错误信息class
  16. errorClass: 'has-error',
  17. // 表单错误信息容器选择器
  18. errorContainerSelector: '.with-errors',
  19. // 表单组css选择器
  20. groupSelector: '.form-group,.form-label-group,.form-field',
  21. // tab表单css选择器
  22. tabSelector: '.tab-pane',
  23. // 错误信息模板
  24. errorTemplate: '<label class="control-label" for="inputError"><i class="feather icon-x-circle"></i> {message}</label><br/>',
  25. // 是否允许跳转
  26. redirect: true,
  27. // 保存成功后自动跳转
  28. autoRedirect: false,
  29. // 自动移除表单错误信息
  30. autoRemoveError: true,
  31. // 表单提交之前事件监听,返回false可以中止表单继续提交
  32. before: function () {},
  33. // 表单提交之后事件监听,返回false可以中止后续逻辑
  34. after: function () {},
  35. // 成功事件,返回false可以中止后续逻辑
  36. success: function () {},
  37. // 失败事件,返回false可以中止后续逻辑
  38. error: function () {},
  39. }, options);
  40. _this.originalValues = {};
  41. _this.$form = $(_this.options.form).first();
  42. _this._errColumns = {};
  43. _this.submit();
  44. }
  45. submit() {
  46. let _this = this;
  47. let confirm = _this.options.confirm;
  48. if (! confirm.title) {
  49. return _this._ajaxSubmit();
  50. }
  51. Dcat.confirm(confirm.title, confirm.content, function () {
  52. _this._ajaxSubmit();
  53. });
  54. }
  55. _ajaxSubmit() {
  56. let Dcat = window.Dcat,
  57. _this = this,
  58. $form = _this.$form,
  59. options = _this.options,
  60. $submitButton = $form.find('[type="submit"],.submit');
  61. // 移除所有错误信息
  62. _this.removeErrors();
  63. $form.ajaxSubmit({
  64. beforeSubmit: function (fields, form, _opt) {
  65. if (options.before(fields, form, _opt, _this) === false) {
  66. return false;
  67. }
  68. // 触发全局事件
  69. if (fire(formCallbacks.before, fields, form, _opt, _this) === false) {
  70. return false;
  71. }
  72. // 开启表单验证
  73. if (options.validate) {
  74. $form.validator('validate');
  75. if ($form.find('.' + options.errorClass).length > 0) {
  76. return false;
  77. }
  78. }
  79. $submitButton.buttonLoading();
  80. },
  81. success: function (response) {
  82. $submitButton.buttonLoading(false);
  83. if (options.after(true, response, _this) === false) {
  84. return;
  85. }
  86. if (options.success(response, _this) === false) {
  87. return;
  88. }
  89. if (fire(formCallbacks.success, response, _this) === false) {
  90. return;
  91. }
  92. if (! response.status) {
  93. Dcat.error(response.message || 'Save failed!');
  94. return;
  95. }
  96. Dcat.success(response.message || 'Save succeeded!');
  97. if (typeof response.location !== "undefined") {
  98. return setTimeout(function () {
  99. if (response.location) {
  100. location.href = response.location;
  101. } else {
  102. location.reload();
  103. }
  104. }, 1500)
  105. }
  106. if (response.redirect === false || ! options.redirect) {
  107. return;
  108. }
  109. if (response.redirect) {
  110. return Dcat.reload(response.redirect);
  111. }
  112. if (options.autoRedirect) {
  113. history.back(-1);
  114. }
  115. },
  116. error: function (response) {
  117. $submitButton.buttonLoading(false);
  118. if (options.after(false, response, _this) === false) {
  119. return;
  120. }
  121. if (options.error(response, _this) === false) {
  122. return;
  123. }
  124. if (fire(formCallbacks.error, response, _this) === false) {
  125. return;
  126. }
  127. try {
  128. var error = JSON.parse(response.responseText),
  129. key;
  130. if (response.status != 422 || ! error || ! Dcat.helpers.isset(error, 'errors')) {
  131. return Dcat.error(response.status + ' ' + response.statusText);
  132. }
  133. error = error.errors;
  134. for (key in error) {
  135. // 显示错误信息
  136. _this._errColumns[key] = _this.showError($form, key, error[key]);
  137. }
  138. } catch (e) {
  139. return Dcat.error(response.status + ' ' + response.statusText);
  140. }
  141. }
  142. });
  143. }
  144. // 显示错误信息
  145. showError($form, column, errors) {
  146. let _this = this,
  147. $field = _this.queryFieldByName($form, column),
  148. $group = $field.closest(_this.options.groupSelector),
  149. render = function (msg) {
  150. $group.addClass(_this.options.errorClass);
  151. if (typeof msg === 'string') {
  152. msg = [msg];
  153. }
  154. for (let j in msg) {
  155. $group.find(_this.options.errorContainerSelector).first().append(
  156. _this.options.errorTemplate.replace('{message}', msg[j])
  157. );
  158. }
  159. };
  160. queryTabTitleError(_this, $field).removeClass('d-none');
  161. // 保存字段原始数据
  162. _this.originalValues[column] = _this.getFieldValue($field);
  163. if (! $field) {
  164. if (Dcat.helpers.len(errors) && errors.length) {
  165. Dcat.error(errors.join(" \n "));
  166. }
  167. return;
  168. }
  169. render(errors);
  170. if (_this.options.autoRemoveError) {
  171. removeErrorWhenValChanged(_this, $field, column);
  172. }
  173. return $field;
  174. }
  175. // 获取字段值
  176. getFieldValue($field) {
  177. let vals = [],
  178. type = $field.attr('type'),
  179. checker = type === 'checkbox' || type === 'radio',
  180. i;
  181. for (i = 0; i < $field.length; i++) {
  182. if (checker) {
  183. vals.push($($field[i]).prop('checked'));
  184. continue;
  185. }
  186. vals.push($($field[i]).val());
  187. }
  188. return vals;
  189. }
  190. // 判断值是否改变
  191. isValueChanged($field, column) {
  192. return ! Dcat.helpers.equal(this.originalValues[column], this.getFieldValue($field));
  193. }
  194. // 获取字段jq对象
  195. queryFieldByName($form, column) {
  196. if (column.indexOf('.') !== -1) {
  197. column = column.split('.');
  198. let first = column.shift(),
  199. i,
  200. sub = '';
  201. for (i in column) {
  202. sub += '[' + column[i] + ']';
  203. }
  204. column = first + sub;
  205. }
  206. var $c = $form.find('[name="' + column + '"]');
  207. if (!$c.length) $c = $form.find('[name="' + column + '[]"]');
  208. if (!$c.length) {
  209. $c = $form.find('[name="' + column.replace(/start$/, '') + '"]');
  210. }
  211. if (!$c.length) {
  212. $c = $form.find('[name="' + column.replace(/end$/, '') + '"]');
  213. }
  214. if (!$c.length) {
  215. $c = $form.find('[name="' + column.replace(/start\]$/, ']') + '"]');
  216. }
  217. if (!$c.length) {
  218. $c = $form.find('[name="' + column.replace(/end\]$/, ']') + '"]');
  219. }
  220. return $c;
  221. }
  222. // 移除给定字段的错误信息
  223. removeError($field, column) {
  224. let options = this.options,
  225. parent = $field.parents(options.groupSelector),
  226. errorClass = this.errorClass;
  227. parent.removeClass(errorClass);
  228. parent.find(options.errorContainerSelector).html('');
  229. // tab页下没有错误信息了,隐藏title的错误图标
  230. let tab;
  231. if (! queryTabByField(this, $field).find('.'+errorClass).length) {
  232. tab = queryTabTitleError(this, $field);
  233. if (! tab.hasClass('d-none')) {
  234. tab.addClass('d-none');
  235. }
  236. }
  237. delete this._errColumns[column];
  238. }
  239. // 删除所有错误信息
  240. removeErrors() {
  241. let _this = this,
  242. column,
  243. tab;
  244. // 移除所有字段的错误信息
  245. _this.$form.find(_this.options.errorContainerSelector).each(function (_, $err) {
  246. $($err).parents(_this.options.groupSelector).removeClass(_this.options.errorClass);
  247. $($err).html('');
  248. });
  249. // 移除tab表单tab标题错误信息
  250. for (column in _this._errColumns) {
  251. tab = queryTabTitleError(_this._errColumns[column]);
  252. if (! tab.hasClass('d-none')) {
  253. tab.addClass('d-none');
  254. }
  255. }
  256. // 重置
  257. _this._errColumns = {};
  258. }
  259. }
  260. // 监听表单提交事件
  261. Form.submitting = function (callback) {
  262. typeof callback == 'function' && (formCallbacks.before.push(callback));
  263. return this
  264. };
  265. // 监听表单提交完毕事件
  266. Form.submitted = function (success, error) {
  267. typeof success == 'function' && (formCallbacks.success.push(success));
  268. typeof error == 'function' && (formCallbacks.error.push(error));
  269. return this
  270. };
  271. // 当字段值变化时移除错误信息
  272. function removeErrorWhenValChanged(form, $field, column) {
  273. let remove = function () {
  274. form.removeError($field, column)
  275. };
  276. $field.one('change', remove);
  277. $field.off('blur', remove).on('blur', function () {
  278. if (form.isValueChanged($field, column)) {
  279. remove();
  280. }
  281. });
  282. // 表单值发生变化就移除错误信息
  283. let interval = function () {
  284. setTimeout(function () {
  285. if (! $field.length) {
  286. return;
  287. }
  288. if (form.isValueChanged($field, column)) {
  289. return remove();
  290. }
  291. interval();
  292. }, 500);
  293. };
  294. interval();
  295. }
  296. function getTabId(form, $field) {
  297. return $field.parents(form.options.tabSelector).attr('id');
  298. }
  299. function queryTabByField(form, $field)
  300. {
  301. let tabId = getTabId(form, $field);
  302. if (! tabId) {
  303. return $('<none></none>');
  304. }
  305. return $(`a[href="#${tabId}"]`);
  306. }
  307. function queryTabTitleError(form, $field) {
  308. return queryTabByField(form, $field).find('.has-tab-error');
  309. }
  310. // 触发钩子事件
  311. function fire(callbacks) {
  312. let i, j,
  313. result,
  314. args = arguments,
  315. argsArr = [];
  316. delete args[0];
  317. args = args || [];
  318. for (j in args) {
  319. argsArr.push(args[j]);
  320. }
  321. for (i in callbacks) {
  322. result = callbacks[i].apply(callbacks[i], argsArr);
  323. if (result === false) {
  324. return result; // 返回 false 会代码阻止继续执行
  325. }
  326. }
  327. }
  328. // 开启form表单模式
  329. $.fn.form = function (options) {
  330. let $this = $(this);
  331. options = $.extend(options, {
  332. form: $this,
  333. });
  334. $this.on('submit', function () {
  335. return false;
  336. });
  337. $this.find('[type="submit"],.submit').click(function (e) {
  338. Dcat.Form(options);
  339. return false;
  340. });
  341. };
  342. export default Form