yii.activeForm.js 31 KB

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