yii.activeForm.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. /**
  2. * Yii form widget.
  3. *
  4. * This is the JavaScript widget used by the yii\widgets\ActiveForm widget.
  5. *
  6. * @link http://www.yiiframework.com/
  7. * @copyright Copyright (c) 2008 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. * @author Qiang Xue <qiang.xue@gmail.com>
  10. * @since 2.0
  11. */
  12. (function ($) {
  13. $.fn.yiiActiveForm = function (method) {
  14. if (methods[method]) {
  15. return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  16. } else {
  17. if (typeof method === 'object' || !method) {
  18. return methods.init.apply(this, arguments);
  19. } else {
  20. $.error('Method ' + method + ' does not exist on jQuery.yiiActiveForm');
  21. return false;
  22. }
  23. }
  24. };
  25. var events = {
  26. /**
  27. * beforeValidate event is triggered before validating the whole form.
  28. * The signature of the event handler should be:
  29. * function (event, messages, deferreds)
  30. * where
  31. * - event: an Event object.
  32. * - messages: an associative array with keys being attribute IDs and values being error message arrays
  33. * for the corresponding attributes.
  34. * - deferreds: an array of Deferred objects. You can use deferreds.add(callback) to add a new deferred validation.
  35. *
  36. * If the handler returns a boolean false, it will stop further form validation after this event. And as
  37. * a result, afterValidate event will not be triggered.
  38. */
  39. beforeValidate: 'beforeValidate',
  40. /**
  41. * afterValidate event is triggered after validating the whole form.
  42. * The signature of the event handler should be:
  43. * function (event, messages, errorAttributes)
  44. * where
  45. * - event: an Event object.
  46. * - messages: an associative array with keys being attribute IDs and values being error message arrays
  47. * for the corresponding attributes.
  48. * - errorAttributes: an array of attributes that have validation errors. Please refer to attributeDefaults for the structure of this parameter.
  49. */
  50. afterValidate: 'afterValidate',
  51. /**
  52. * beforeValidateAttribute event is triggered before validating an attribute.
  53. * The signature of the event handler should be:
  54. * function (event, attribute, messages, deferreds)
  55. * where
  56. * - event: an Event object.
  57. * - attribute: the attribute to be validated. Please refer to attributeDefaults for the structure of this parameter.
  58. * - messages: an array to which you can add validation error messages for the specified attribute.
  59. * - deferreds: an array of Deferred objects. You can use deferreds.add(callback) to add a new deferred validation.
  60. *
  61. * If the handler returns a boolean false, it will stop further validation of the specified attribute.
  62. * And as a result, afterValidateAttribute event will not be triggered.
  63. */
  64. beforeValidateAttribute: 'beforeValidateAttribute',
  65. /**
  66. * afterValidateAttribute event is triggered after validating the whole form and each attribute.
  67. * The signature of the event handler should be:
  68. * function (event, attribute, messages)
  69. * where
  70. * - event: an Event object.
  71. * - attribute: the attribute being validated. Please refer to attributeDefaults for the structure of this parameter.
  72. * - messages: an array to which you can add additional validation error messages for the specified attribute.
  73. */
  74. afterValidateAttribute: 'afterValidateAttribute',
  75. /**
  76. * beforeSubmit event is triggered before submitting the form after all validations have passed.
  77. * The signature of the event handler should be:
  78. * function (event)
  79. * where event is an Event object.
  80. *
  81. * If the handler returns a boolean false, it will stop form submission.
  82. */
  83. beforeSubmit: 'beforeSubmit',
  84. /**
  85. * ajaxBeforeSend event is triggered before sending an AJAX request for AJAX-based validation.
  86. * The signature of the event handler should be:
  87. * function (event, jqXHR, settings)
  88. * where
  89. * - event: an Event object.
  90. * - jqXHR: a jqXHR object
  91. * - settings: the settings for the AJAX request
  92. */
  93. ajaxBeforeSend: 'ajaxBeforeSend',
  94. /**
  95. * ajaxComplete event is triggered after completing an AJAX request for AJAX-based validation.
  96. * The signature of the event handler should be:
  97. * function (event, jqXHR, textStatus)
  98. * where
  99. * - event: an Event object.
  100. * - jqXHR: a jqXHR object
  101. * - textStatus: the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror").
  102. */
  103. ajaxComplete: 'ajaxComplete',
  104. /**
  105. * afterInit event is triggered after yii activeForm init.
  106. * The signature of the event handler should be:
  107. * function (event)
  108. * where
  109. * - event: an Event object.
  110. */
  111. afterInit: 'afterInit'
  112. };
  113. // NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveForm::getClientOptions() as well
  114. var defaults = {
  115. // whether to encode the error summary
  116. encodeErrorSummary: true,
  117. // the jQuery selector for the error summary
  118. errorSummary: '.error-summary',
  119. // whether to perform validation before submitting the form.
  120. validateOnSubmit: true,
  121. // the container CSS class representing the corresponding attribute has validation error
  122. errorCssClass: 'has-error',
  123. // the container CSS class representing the corresponding attribute passes validation
  124. successCssClass: 'has-success',
  125. // the container CSS class representing the corresponding attribute is being validated
  126. validatingCssClass: 'validating',
  127. // the GET parameter name indicating an AJAX-based validation
  128. ajaxParam: 'ajax',
  129. // the type of data that you're expecting back from the server
  130. ajaxDataType: 'json',
  131. // the URL for performing AJAX-based validation. If not set, it will use the the form's action
  132. validationUrl: undefined,
  133. // whether to scroll to first visible error after validation.
  134. scrollToError: true,
  135. // offset in pixels that should be added when scrolling to the first error.
  136. scrollToErrorOffset: 0,
  137. // where to add validation class: container or input
  138. validationStateOn: 'container'
  139. };
  140. // NOTE: If you change any of these defaults, make sure you update yii\widgets\ActiveField::getClientOptions() as well
  141. var attributeDefaults = {
  142. // a unique ID identifying an attribute (e.g. "loginform-username") in a form
  143. id: undefined,
  144. // attribute name or expression (e.g. "[0]content" for tabular input)
  145. name: undefined,
  146. // the jQuery selector of the container of the input field
  147. container: undefined,
  148. // the jQuery selector of the input field under the context of the form
  149. input: undefined,
  150. // the jQuery selector of the error tag under the context of the container
  151. error: '.help-block',
  152. // whether to encode the error
  153. encodeError: true,
  154. // whether to perform validation when a change is detected on the input
  155. validateOnChange: true,
  156. // whether to perform validation when the input loses focus
  157. validateOnBlur: true,
  158. // whether to perform validation when the user is typing.
  159. validateOnType: false,
  160. // number of milliseconds that the validation should be delayed when a user is typing in the input field.
  161. validationDelay: 500,
  162. // whether to enable AJAX-based validation.
  163. enableAjaxValidation: false,
  164. // function (attribute, value, messages, deferred, $form), the client-side validation function.
  165. validate: undefined,
  166. // status of the input field, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
  167. status: 0,
  168. // whether the validation is cancelled by beforeValidateAttribute event handler
  169. cancelled: false,
  170. // the value of the input
  171. value: undefined,
  172. // whether to update aria-invalid attribute after validation
  173. updateAriaInvalid: true
  174. };
  175. var submitDefer;
  176. var setSubmitFinalizeDefer = function ($form) {
  177. submitDefer = $.Deferred();
  178. $form.data('yiiSubmitFinalizePromise', submitDefer.promise());
  179. };
  180. // finalize yii.js $form.submit
  181. var submitFinalize = function ($form) {
  182. if (submitDefer) {
  183. submitDefer.resolve();
  184. submitDefer = undefined;
  185. $form.removeData('yiiSubmitFinalizePromise');
  186. }
  187. };
  188. var methods = {
  189. init: function (attributes, options) {
  190. return this.each(function () {
  191. var $form = $(this);
  192. if ($form.data('yiiActiveForm')) {
  193. return;
  194. }
  195. var settings = $.extend({}, defaults, options || {});
  196. if (settings.validationUrl === undefined) {
  197. settings.validationUrl = $form.attr('action');
  198. }
  199. $.each(attributes, function (i) {
  200. attributes[i] = $.extend({value: getValue($form, this)}, attributeDefaults, this);
  201. watchAttribute($form, attributes[i]);
  202. });
  203. $form.data('yiiActiveForm', {
  204. settings: settings,
  205. attributes: attributes,
  206. submitting: false,
  207. validated: false,
  208. options: getFormOptions($form)
  209. });
  210. /**
  211. * Clean up error status when the form is reset.
  212. * Note that $form.on('reset', ...) does work because the "reset" event does not bubble on IE.
  213. */
  214. $form.on('reset.yiiActiveForm', methods.resetForm);
  215. if (settings.validateOnSubmit) {
  216. $form.on('mouseup.yiiActiveForm keyup.yiiActiveForm', ':submit', function () {
  217. $form.data('yiiActiveForm').submitObject = $(this);
  218. });
  219. $form.on('submit.yiiActiveForm', methods.submitForm);
  220. }
  221. var event = $.Event(events.afterInit);
  222. $form.trigger(event);
  223. });
  224. },
  225. // add a new attribute to the form dynamically.
  226. // please refer to attributeDefaults for the structure of attribute
  227. add: function (attribute) {
  228. var $form = $(this);
  229. attribute = $.extend({value: getValue($form, attribute)}, attributeDefaults, attribute);
  230. $form.data('yiiActiveForm').attributes.push(attribute);
  231. watchAttribute($form, attribute);
  232. },
  233. // remove the attribute with the specified ID from the form
  234. remove: function (id) {
  235. var $form = $(this),
  236. attributes = $form.data('yiiActiveForm').attributes,
  237. index = -1,
  238. attribute = undefined;
  239. $.each(attributes, function (i) {
  240. if (attributes[i]['id'] == id) {
  241. index = i;
  242. attribute = attributes[i];
  243. return false;
  244. }
  245. });
  246. if (index >= 0) {
  247. attributes.splice(index, 1);
  248. unwatchAttribute($form, attribute);
  249. }
  250. return attribute;
  251. },
  252. // manually trigger the validation of the attribute with the specified ID
  253. validateAttribute: function (id) {
  254. var attribute = methods.find.call(this, id);
  255. if (attribute != undefined) {
  256. validateAttribute($(this), attribute, true);
  257. }
  258. },
  259. // find an attribute config based on the specified attribute ID
  260. find: function (id) {
  261. var attributes = $(this).data('yiiActiveForm').attributes,
  262. result = undefined;
  263. $.each(attributes, function (i) {
  264. if (attributes[i]['id'] == id) {
  265. result = attributes[i];
  266. return false;
  267. }
  268. });
  269. return result;
  270. },
  271. destroy: function () {
  272. return this.each(function () {
  273. $(this).off('.yiiActiveForm');
  274. $(this).removeData('yiiActiveForm');
  275. });
  276. },
  277. data: function () {
  278. return this.data('yiiActiveForm');
  279. },
  280. // validate all applicable inputs in the form
  281. validate: function (forceValidate) {
  282. if (forceValidate) {
  283. $(this).data('yiiActiveForm').submitting = true;
  284. }
  285. var $form = $(this),
  286. data = $form.data('yiiActiveForm'),
  287. needAjaxValidation = false,
  288. messages = {},
  289. deferreds = deferredArray(),
  290. submitting = data.submitting;
  291. if (submitting) {
  292. var event = $.Event(events.beforeValidate);
  293. $form.trigger(event, [messages, deferreds]);
  294. if (event.result === false) {
  295. data.submitting = false;
  296. submitFinalize($form);
  297. return;
  298. }
  299. }
  300. // client-side validation
  301. $.each(data.attributes, function () {
  302. this.$form = $form;
  303. var $input = findInput($form, this);
  304. var disabled = $input.toArray().reduce(function(result, next) {
  305. return result && $(next).is(':disabled');
  306. }, true);
  307. if (disabled) {
  308. return true;
  309. }
  310. // validate markup for select input
  311. if ($input.length && $input[0].tagName.toLowerCase() === 'select') {
  312. var opts = $input[0].options, isEmpty = !opts || !opts.length, isRequired = $input.attr('required'),
  313. isMultiple = $input.attr('multiple'), size = $input.attr('size') || 1;
  314. // check if valid HTML markup for select input, else return validation as `true`
  315. // https://w3c.github.io/html-reference/select.html
  316. if (isRequired && !isMultiple && parseInt(size, 10) === 1) { // invalid select markup condition
  317. if (isEmpty) { // empty option elements for the select
  318. return true;
  319. }
  320. if (opts[0] && (opts[0].value !== '' && opts[0].text !== '')) { // first option is not empty
  321. return true;
  322. }
  323. }
  324. }
  325. this.cancelled = false;
  326. // perform validation only if the form is being submitted or if an attribute is pending validation
  327. if (data.submitting || this.status === 2 || this.status === 3) {
  328. var msg = messages[this.id];
  329. if (msg === undefined) {
  330. msg = [];
  331. messages[this.id] = msg;
  332. }
  333. var event = $.Event(events.beforeValidateAttribute);
  334. $form.trigger(event, [this, msg, deferreds]);
  335. if (event.result !== false) {
  336. if (this.validate) {
  337. this.validate(this, getValue($form, this), msg, deferreds, $form);
  338. }
  339. if (this.enableAjaxValidation) {
  340. needAjaxValidation = true;
  341. }
  342. } else {
  343. this.cancelled = true;
  344. }
  345. }
  346. });
  347. // ajax validation
  348. $.when.apply(this, deferreds).always(function () {
  349. // Remove empty message arrays
  350. for (var i in messages) {
  351. if (0 === messages[i].length) {
  352. delete messages[i];
  353. }
  354. }
  355. if (needAjaxValidation && ($.isEmptyObject(messages) || data.submitting)) {
  356. var $button = data.submitObject,
  357. extData = '&' + data.settings.ajaxParam + '=' + $form.attr('id');
  358. if ($button && $button.length && $button.attr('name')) {
  359. extData += '&' + $button.attr('name') + '=' + $button.attr('value');
  360. }
  361. $.ajax({
  362. url: data.settings.validationUrl,
  363. type: $form.attr('method'),
  364. data: $form.serialize() + extData,
  365. dataType: data.settings.ajaxDataType,
  366. complete: function (jqXHR, textStatus) {
  367. $form.trigger(events.ajaxComplete, [jqXHR, textStatus]);
  368. },
  369. beforeSend: function (jqXHR, settings) {
  370. $form.trigger(events.ajaxBeforeSend, [jqXHR, settings]);
  371. },
  372. success: function (msgs) {
  373. if (msgs !== null && typeof msgs === 'object') {
  374. $.each(data.attributes, function () {
  375. if (!this.enableAjaxValidation || this.cancelled) {
  376. delete msgs[this.id];
  377. }
  378. });
  379. updateInputs($form, $.extend(messages, msgs), submitting);
  380. } else {
  381. updateInputs($form, messages, submitting);
  382. }
  383. },
  384. error: function () {
  385. data.submitting = false;
  386. submitFinalize($form);
  387. }
  388. });
  389. } else {
  390. if (data.submitting) {
  391. // delay callback so that the form can be submitted without problem
  392. window.setTimeout(function () {
  393. updateInputs($form, messages, submitting);
  394. }, 200);
  395. } else {
  396. updateInputs($form, messages, submitting);
  397. }
  398. }
  399. });
  400. },
  401. submitForm: function () {
  402. var $form = $(this),
  403. data = $form.data('yiiActiveForm');
  404. if (data.validated) {
  405. // Second submit's call (from validate/updateInputs)
  406. data.submitting = false;
  407. var event = $.Event(events.beforeSubmit);
  408. $form.trigger(event);
  409. if (event.result === false) {
  410. data.validated = false;
  411. submitFinalize($form);
  412. return false;
  413. }
  414. updateHiddenButton($form);
  415. return true; // continue submitting the form since validation passes
  416. } else {
  417. // First submit's call (from yii.js/handleAction) - execute validating
  418. setSubmitFinalizeDefer($form);
  419. if (data.settings.timer !== undefined) {
  420. clearTimeout(data.settings.timer);
  421. }
  422. data.submitting = true;
  423. methods.validate.call($form);
  424. return false;
  425. }
  426. },
  427. resetForm: function () {
  428. var $form = $(this);
  429. var data = $form.data('yiiActiveForm');
  430. // Because we bind directly to a form reset event instead of a reset button (that may not exist),
  431. // when this function is executed form input values have not been reset yet.
  432. // Therefore we do the actual reset work through setTimeout.
  433. window.setTimeout(function () {
  434. $.each(data.attributes, function () {
  435. // Without setTimeout() we would get the input values that are not reset yet.
  436. this.value = getValue($form, this);
  437. this.status = 0;
  438. var $container = $form.find(this.container),
  439. $input = findInput($form, this),
  440. $errorElement = data.settings.validationStateOn === 'input' ? $input : $container;
  441. $errorElement.removeClass(
  442. data.settings.validatingCssClass + ' ' +
  443. data.settings.errorCssClass + ' ' +
  444. data.settings.successCssClass
  445. );
  446. $container.find(this.error).html('');
  447. });
  448. $form.find(data.settings.errorSummary).hide().find('ul').html('');
  449. }, 1);
  450. },
  451. /**
  452. * Updates error messages, input containers, and optionally summary as well.
  453. * If an attribute is missing from messages, it is considered valid.
  454. * @param messages array the validation error messages, indexed by attribute IDs
  455. * @param summary whether to update summary as well.
  456. */
  457. updateMessages: function (messages, summary) {
  458. var $form = $(this);
  459. var data = $form.data('yiiActiveForm');
  460. $.each(data.attributes, function () {
  461. updateInput($form, this, messages);
  462. });
  463. if (summary) {
  464. updateSummary($form, messages);
  465. }
  466. },
  467. /**
  468. * Updates error messages and input container of a single attribute.
  469. * If messages is empty, the attribute is considered valid.
  470. * @param id attribute ID
  471. * @param messages array with error messages
  472. */
  473. updateAttribute: function (id, messages) {
  474. var attribute = methods.find.call(this, id);
  475. if (attribute != undefined) {
  476. var msg = {};
  477. msg[id] = messages;
  478. updateInput($(this), attribute, msg);
  479. }
  480. }
  481. };
  482. var watchAttribute = function ($form, attribute) {
  483. var $input = findInput($form, attribute);
  484. if (attribute.validateOnChange) {
  485. $input.on('change.yiiActiveForm', function () {
  486. validateAttribute($form, attribute, false);
  487. });
  488. }
  489. if (attribute.validateOnBlur) {
  490. $input.on('blur.yiiActiveForm', function () {
  491. if (attribute.status == 0 || attribute.status == 1) {
  492. validateAttribute($form, attribute, true);
  493. }
  494. });
  495. }
  496. if (attribute.validateOnType) {
  497. $input.on('keyup.yiiActiveForm', function (e) {
  498. if ($.inArray(e.which, [16, 17, 18, 37, 38, 39, 40]) !== -1) {
  499. return;
  500. }
  501. if (attribute.value !== getValue($form, attribute)) {
  502. validateAttribute($form, attribute, false, attribute.validationDelay);
  503. }
  504. });
  505. }
  506. };
  507. var unwatchAttribute = function ($form, attribute) {
  508. findInput($form, attribute).off('.yiiActiveForm');
  509. };
  510. var validateAttribute = function ($form, attribute, forceValidate, validationDelay) {
  511. var data = $form.data('yiiActiveForm');
  512. if (forceValidate) {
  513. attribute.status = 2;
  514. }
  515. $.each(data.attributes, function () {
  516. if (!isEqual(this.value, getValue($form, this))) {
  517. this.status = 2;
  518. forceValidate = true;
  519. }
  520. });
  521. if (!forceValidate) {
  522. return;
  523. }
  524. if (data.settings.timer !== undefined) {
  525. clearTimeout(data.settings.timer);
  526. }
  527. data.settings.timer = window.setTimeout(function () {
  528. if (data.submitting || $form.is(':hidden')) {
  529. return;
  530. }
  531. $.each(data.attributes, function () {
  532. if (this.status === 2) {
  533. this.status = 3;
  534. var $container = $form.find(this.container),
  535. $input = findInput($form, this);
  536. var $errorElement = data.settings.validationStateOn === 'input' ? $input : $container;
  537. $errorElement.addClass(data.settings.validatingCssClass);
  538. }
  539. });
  540. methods.validate.call($form);
  541. }, validationDelay ? validationDelay : 200);
  542. };
  543. /**
  544. * Compares two value whatever it objects, arrays or simple types
  545. * @param val1
  546. * @param val2
  547. * @returns boolean
  548. */
  549. var isEqual = function (val1, val2) {
  550. // objects
  551. if (val1 instanceof Object) {
  552. return isObjectsEqual(val1, val2)
  553. }
  554. // arrays
  555. if (Array.isArray(val1)) {
  556. return isArraysEqual(val1, val2);
  557. }
  558. // simple types
  559. return val1 === val2;
  560. };
  561. /**
  562. * Compares two objects
  563. * @param obj1
  564. * @param obj2
  565. * @returns boolean
  566. */
  567. var isObjectsEqual = function (obj1, obj2) {
  568. if (!(obj1 instanceof Object) || !(obj2 instanceof Object)) {
  569. return false;
  570. }
  571. var keys1 = Object.keys(obj1);
  572. var keys2 = Object.keys(obj2);
  573. if (keys1.length !== keys2.length) {
  574. return false;
  575. }
  576. for (var i = 0; i < keys1.length; i += 1) {
  577. if (!obj2.hasOwnProperty(keys1[i])) {
  578. return false;
  579. }
  580. if (obj1[keys1[i]] !== obj2[keys1[i]]) {
  581. return false;
  582. }
  583. }
  584. return true;
  585. };
  586. /**
  587. * Compares two arrays
  588. * @param arr1
  589. * @param arr2
  590. * @returns boolean
  591. */
  592. var isArraysEqual = function (arr1, arr2) {
  593. if (!Array.isArray(arr1) || !Array.isArray(arr2)) {
  594. return false;
  595. }
  596. if (arr1.length !== arr2.length) {
  597. return false;
  598. }
  599. for (var i = 0; i < arr1.length; i += 1) {
  600. if (arr1[i] !== arr2[i]) {
  601. return false;
  602. }
  603. }
  604. return true;
  605. };
  606. /**
  607. * Returns an array prototype with a shortcut method for adding a new deferred.
  608. * The context of the callback will be the deferred object so it can be resolved like ```this.resolve()```
  609. * @returns Array
  610. */
  611. var deferredArray = function () {
  612. var array = [];
  613. array.add = function (callback) {
  614. this.push(new $.Deferred(callback));
  615. };
  616. return array;
  617. };
  618. var buttonOptions = ['action', 'target', 'method', 'enctype'];
  619. /**
  620. * Returns current form options
  621. * @param $form
  622. * @returns object Object with button of form options
  623. */
  624. var getFormOptions = function ($form) {
  625. var attributes = {};
  626. for (var i = 0; i < buttonOptions.length; i++) {
  627. attributes[buttonOptions[i]] = $form.attr(buttonOptions[i]);
  628. }
  629. return attributes;
  630. };
  631. /**
  632. * Applies temporary form options related to submit button
  633. * @param $form the form jQuery object
  634. * @param $button the button jQuery object
  635. */
  636. var applyButtonOptions = function ($form, $button) {
  637. for (var i = 0; i < buttonOptions.length; i++) {
  638. var value = $button.attr('form' + buttonOptions[i]);
  639. if (value) {
  640. $form.attr(buttonOptions[i], value);
  641. }
  642. }
  643. };
  644. /**
  645. * Restores original form options
  646. * @param $form the form jQuery object
  647. */
  648. var restoreButtonOptions = function ($form) {
  649. var data = $form.data('yiiActiveForm');
  650. for (var i = 0; i < buttonOptions.length; i++) {
  651. $form.attr(buttonOptions[i], data.options[buttonOptions[i]] || null);
  652. }
  653. };
  654. /**
  655. * Updates the error messages and the input containers for all applicable attributes
  656. * @param $form the form jQuery object
  657. * @param messages array the validation error messages
  658. * @param submitting whether this method is called after validation triggered by form submission
  659. */
  660. var updateInputs = function ($form, messages, submitting) {
  661. var data = $form.data('yiiActiveForm');
  662. if (data === undefined) {
  663. return false;
  664. }
  665. var errorAttributes = [], $input;
  666. $.each(data.attributes, function () {
  667. var hasError = (submitting && updateInput($form, this, messages)) || (!submitting && attrHasError($form,
  668. this, messages));
  669. $input = findInput($form, this);
  670. if (!$input.is(':disabled') && !this.cancelled && hasError) {
  671. errorAttributes.push(this);
  672. }
  673. });
  674. $form.trigger(events.afterValidate, [messages, errorAttributes]);
  675. if (submitting) {
  676. updateSummary($form, messages);
  677. if (errorAttributes.length) {
  678. if (data.settings.scrollToError) {
  679. var h = $(document).height(), top = $form.find($.map(errorAttributes, function (attribute) {
  680. return attribute.input;
  681. }).join(',')).first().closest(':visible').offset().top - data.settings.scrollToErrorOffset;
  682. top = top < 0 ? 0 : (top > h ? h : top);
  683. var wtop = $(window).scrollTop();
  684. if (top < wtop || top > wtop + $(window).height()) {
  685. $(window).scrollTop(top);
  686. }
  687. }
  688. data.submitting = false;
  689. } else {
  690. data.validated = true;
  691. if (data.submitObject) {
  692. applyButtonOptions($form, data.submitObject);
  693. }
  694. $form.submit();
  695. if (data.submitObject) {
  696. restoreButtonOptions($form);
  697. }
  698. }
  699. } else {
  700. $.each(data.attributes, function () {
  701. if (!this.cancelled && (this.status === 2 || this.status === 3)) {
  702. updateInput($form, this, messages);
  703. }
  704. });
  705. }
  706. submitFinalize($form);
  707. };
  708. /**
  709. * Updates hidden field that represents clicked submit button.
  710. * @param $form the form jQuery object.
  711. */
  712. var updateHiddenButton = function ($form) {
  713. var data = $form.data('yiiActiveForm');
  714. var $button = data.submitObject || $form.find(':submit:first');
  715. // TODO: if the submission is caused by "change" event, it will not work
  716. if ($button.length && $button.attr('type') == 'submit' && $button.attr('name')) {
  717. // simulate button input value
  718. var $hiddenButton = $('input[type="hidden"][name="' + $button.attr('name') + '"]', $form);
  719. if (!$hiddenButton.length) {
  720. $('<input>').attr({
  721. type: 'hidden',
  722. name: $button.attr('name'),
  723. value: $button.attr('value')
  724. }).appendTo($form);
  725. } else {
  726. $hiddenButton.attr('value', $button.attr('value'));
  727. }
  728. }
  729. };
  730. /**
  731. * Updates the error message and the input container for a particular attribute.
  732. * @param $form the form jQuery object
  733. * @param attribute object the configuration for a particular attribute.
  734. * @param messages array the validation error messages
  735. * @return boolean whether there is a validation error for the specified attribute
  736. */
  737. var updateInput = function ($form, attribute, messages) {
  738. var data = $form.data('yiiActiveForm'),
  739. $input = findInput($form, attribute),
  740. hasError = attrHasError($form, attribute, messages);
  741. if (!$.isArray(messages[attribute.id])) {
  742. messages[attribute.id] = [];
  743. }
  744. attribute.status = 1;
  745. if ($input.length) {
  746. var $container = $form.find(attribute.container);
  747. var $error = $container.find(attribute.error);
  748. updateAriaInvalid($form, attribute, hasError);
  749. var $errorElement = data.settings.validationStateOn === 'input' ? $input : $container;
  750. if (hasError) {
  751. if (attribute.encodeError) {
  752. $error.text(messages[attribute.id][0]);
  753. } else {
  754. $error.html(messages[attribute.id][0]);
  755. }
  756. $errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.successCssClass)
  757. .addClass(data.settings.errorCssClass);
  758. } else {
  759. $error.empty();
  760. $errorElement.removeClass(data.settings.validatingCssClass + ' ' + data.settings.errorCssClass + ' ')
  761. .addClass(data.settings.successCssClass);
  762. }
  763. attribute.value = getValue($form, attribute);
  764. }
  765. $form.trigger(events.afterValidateAttribute, [attribute, messages[attribute.id]]);
  766. return hasError;
  767. };
  768. /**
  769. * Checks if a particular attribute has an error
  770. * @param $form the form jQuery object
  771. * @param attribute object the configuration for a particular attribute.
  772. * @param messages array the validation error messages
  773. * @return boolean whether there is a validation error for the specified attribute
  774. */
  775. var attrHasError = function ($form, attribute, messages) {
  776. var $input = findInput($form, attribute),
  777. hasError = false;
  778. if (!$.isArray(messages[attribute.id])) {
  779. messages[attribute.id] = [];
  780. }
  781. if ($input.length) {
  782. hasError = messages[attribute.id].length > 0;
  783. }
  784. return hasError;
  785. };
  786. /**
  787. * Updates the error summary.
  788. * @param $form the form jQuery object
  789. * @param messages array the validation error messages
  790. */
  791. var updateSummary = function ($form, messages) {
  792. var data = $form.data('yiiActiveForm'),
  793. $summary = $form.find(data.settings.errorSummary),
  794. $ul = $summary.find('ul').empty();
  795. if ($summary.length && messages) {
  796. $.each(data.attributes, function () {
  797. if ($.isArray(messages[this.id]) && messages[this.id].length) {
  798. var error = $('<li/>');
  799. if (data.settings.encodeErrorSummary) {
  800. error.text(messages[this.id][0]);
  801. } else {
  802. error.html(messages[this.id][0]);
  803. }
  804. $ul.append(error);
  805. }
  806. });
  807. $summary.toggle($ul.find('li').length > 0);
  808. }
  809. };
  810. var getValue = function ($form, attribute) {
  811. var $input = findInput($form, attribute);
  812. var type = $input.attr('type');
  813. if (type === 'checkbox' || type === 'radio') {
  814. var $realInput = $input.filter(':checked');
  815. if ($realInput.length > 1) {
  816. var values = [];
  817. $realInput.each(function (index) {
  818. values.push($($realInput.get(index)).val());
  819. });
  820. return values;
  821. }
  822. if (!$realInput.length) {
  823. $realInput = $form.find('input[type=hidden][name="' + $input.attr('name') + '"]');
  824. }
  825. return $realInput.val();
  826. } else {
  827. return $input.val();
  828. }
  829. };
  830. var findInput = function ($form, attribute) {
  831. var $input = $form.find(attribute.input);
  832. if ($input.length && $input[0].tagName.toLowerCase() === 'div') {
  833. // checkbox list or radio list
  834. return $input.find('input');
  835. } else {
  836. return $input;
  837. }
  838. };
  839. var updateAriaInvalid = function ($form, attribute, hasError) {
  840. if (attribute.updateAriaInvalid) {
  841. $form.find(attribute.input).attr('aria-invalid', hasError ? 'true' : 'false');
  842. }
  843. }
  844. })(window.jQuery);