yii.activeForm.js 31KB

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