Form.js 12 KB

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