Yii2 framework backup
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

399 lines
13 KiB

12 years ago
/**
* Yii form widget.
*
* This is the JavaScript widget used by the yii\widgets\ActiveForm widget.
*
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
(function ($) {
$.fn.yiiActiveForm = function (method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist on jQuery.yiiActiveForm');
return false;
}
};
var defaults = {
12 years ago
// the jQuery selector for the error summary
errorSummary: undefined,
12 years ago
// whether to enable client-side (JavaScript) validation
12 years ago
enableClientValidation: true,
12 years ago
// whether to enable AJAX-based validation
enableAjaxValidation: false,
// the URL for performing AJAX-based validation. If not set, it will use the the form's action
12 years ago
validationUrl: undefined,
// number of milliseconds of validation delay. This is used when validateOnType is true.
validationDelay: 200,
// whether to perform validation when a change is detected on the input.
validateOnChange: true,
// whether to perform validation when the user is typing.
validateOnType: false,
12 years ago
// whether to perform validation before submitting the form.
validateOnSubmit: true,
// the container CSS class representing the corresponding attribute has validation error
errorCssClass: 'error',
// the container CSS class representing the corresponding attribute passes validation
successCssClass: 'success',
// the container CSS class representing the corresponding attribute is being validated
validatingCssClass: 'validating',
12 years ago
// a callback that is called before validating any attribute
beforeValidate: undefined,
// a callback that is called after validating any attribute
afterValidate: undefined,
// the GET parameter name indicating an AJAX-based validation
ajaxVar: 'ajax'
12 years ago
};
var methods = {
/**
* Initializes the plugin.
* @param attributes array attribute configurations. Each attribute may contain the following options:
*
* - name: string, attribute name or expression (e.g. "[0]content" for tabular input)
* - container: string, the jQuery selector of the container of the input field
* - input: string, the jQuery selector of the input field
* - error: string, the jQuery selector of the error tag
* - value: string|array, the value of the input
12 years ago
* - validateOnChange: boolean, whether to perform validation when a change is detected on the input.
* If not set, it will take the value of the corresponding global setting.
* - validateOnType: boolean, defaults to false, whether to perform validation when the user is typing.
* If not set, it will take the value of the corresponding global setting.
* - enableAjaxValidation: boolean, whether to enable AJAX-based validation.
* If not set, it will take the value of the corresponding global setting.
* - enableClientValidation: boolean, whether to enable client-side validation.
* If not set, it will take the value of the corresponding global setting.
* - validate: function (attribute, value, messages), the client-side validation function.
* - beforeValidate: function ($form, attribute), callback called before validating an attribute. If it
* returns false, the validation will be cancelled.
* - afterValidate: function ($form, attribute, data, hasError), callback called after validating an attribute.
* - status: integer, 0: empty, not entered before, 1: validated, 2: pending validation, 3: validating
12 years ago
*
* @param options object the configuration for the plugin. The following options can be set:
*/
init: function (attributes, options) {
return this.each(function () {
var $form = $(this);
if ($form.data('yiiActiveForm')) {
return;
}
var settings = $.extend(defaults, options || {});
if (settings.validationUrl === undefined) {
settings.validationUrl = $form.attr('action');
}
$.each(attributes, function (i) {
12 years ago
attributes[i] = $.extend({
validateOnChange: settings.validateOnChange,
validateOnType: settings.validateOnType,
enableAjaxValidation: settings.enableAjaxValidation,
enableClientValidation: settings.enableClientValidation,
value: getValue($form, this)
}, this);
12 years ago
});
$form.data('yiiActiveForm', {
settings: settings,
12 years ago
attributes: attributes,
submitting: false
12 years ago
});
12 years ago
bindAttributes($form, attributes);
12 years ago
12 years ago
/**
12 years ago
* Clean up error status when the form is reset.
* Note that $form.on('reset', ...) does work because the "reset" event does not bubble on IE.
12 years ago
*/
12 years ago
$form.bind('reset.yiiActiveForm', resetForm);
12 years ago
if (settings.validateOnSubmit) {
12 years ago
$form.on('mouseup.yiiActiveForm keyup.yiiActiveForm', ':submit', function () {
12 years ago
$form.data('yiiActiveForm').submitObject = $(this);
12 years ago
});
12 years ago
$form.on('submit', submitForm);
12 years ago
}
});
},
destroy: function () {
return this.each(function () {
$(window).unbind('.yiiActiveForm');
$(this).removeData('yiiActiveForm');
});
12 years ago
}
};
12 years ago
var getValue = function ($form, attribute) {
var $input = findInput($form, attribute);
var type = $input.attr('type');
12 years ago
if (type === 'checkbox' || type === 'radio') {
12 years ago
return $input.filter(':checked').val();
12 years ago
} else {
12 years ago
return $input.val();
12 years ago
}
};
12 years ago
var findInput = function ($form, attribute) {
12 years ago
var $input = $form.find(attribute.input);
if ($input.length && $input[0].tagName.toLowerCase() === 'div') {
12 years ago
// checkbox list or radio list
12 years ago
return $input.find('input');
12 years ago
} else {
12 years ago
return $input;
12 years ago
}
};
12 years ago
var bindAttributes = function ($form, attributes) {
12 years ago
$.each(attributes, function (i, attribute) {
12 years ago
var $input = findInput($form, attribute);
if (attribute.validateOnChange) {
12 years ago
$input.on('change.yiiActiveForm', function () {
validateAttribute($form, attribute, false);
}).on('blur.yiiActiveForm', function () {
if (attribute.status == 0 || attribute.status == 1) {
validateAttribute($form, attribute, !attribute.status);
12 years ago
}
});
12 years ago
}
12 years ago
if (attribute.validateOnType) {
12 years ago
$input.on('keyup.yiiActiveForm', function () {
if (attribute.value !== getValue($form, attribute)) {
validateAttribute($form, attribute, false);
12 years ago
}
});
}
});
};
12 years ago
var validateAttribute = function ($form, attribute, forceValidate) {
var data = $form.data('yiiActiveForm');
if (forceValidate) {
attribute.status = 2;
}
$.each(data.attributes, function () {
if (this.value !== getValue($form, this)) {
this.status = 2;
forceValidate = true;
}
});
if (!forceValidate) {
return;
}
if (data.settings.timer !== undefined) {
clearTimeout(data.settings.timer);
}
data.settings.timer = setTimeout(function () {
if (data.submitting || $form.is(':hidden')) {
return;
}
if (!attribute.beforeValidate || attribute.beforeValidate($form, attribute)) {
$.each(data.attributes, function () {
if (this.status === 2) {
this.status = 3;
$form.find(this.container).addClass(data.settings.validatingCssClass);
}
});
validateForm($form, function (messages) {
var hasError = false;
$.each(data.attributes, function () {
if (this.status === 2 || this.status === 3) {
hasError = updateInput($form, this, messages) || hasError;
}
});
if (attribute.afterValidate) {
attribute.afterValidate($form, attribute, messages, hasError);
}
});
}
}, data.settings.validationDelay);
};
12 years ago
/**
* Performs the ajax validation request.
* This method is invoked internally to trigger the ajax validation.
* @param $form jquery the jquery representation of the form
12 years ago
* @param successCallback function the function to be invoked if the ajax request succeeds
* @param errorCallback function the function to be invoked if the ajax request fails
*/
12 years ago
var validateForm = function ($form, successCallback, errorCallback) {
var data = $form.data('yiiActiveForm'),
12 years ago
needAjaxValidation = false,
messages = {};
12 years ago
$.each(data.attributes, function () {
var msg = [];
if (this.validate && (data.submitting || this.status === 2 || this.status === 3)) {
this.validate(this, getValue($form, this), msg);
12 years ago
if (msg.length) {
12 years ago
messages[this.name] = msg;
12 years ago
}
}
12 years ago
if (this.enableAjaxValidation && !msg.length && (data.submitting || this.status === 2 || this.status === 3)) {
12 years ago
needAjaxValidation = true;
}
});
12 years ago
if (!needAjaxValidation || data.submitting && !$.isEmptyObject(messages)) {
if (data.submitting) {
12 years ago
// delay callback so that the form can be submitted without problem
setTimeout(function () {
successCallback(messages);
}, 200);
} else {
successCallback(messages);
}
return;
}
12 years ago
var $button = data.submitObject,
extData = '&' + data.settings.ajaxVar + '=' + $form.attr('id');
if ($button && $button.length && $button.attr('name')) {
12 years ago
extData += '&' + $button.attr('name') + '=' + $button.attr('value');
}
$.ajax({
12 years ago
url: data.settings.validationUrl,
12 years ago
type: $form.attr('method'),
data: $form.serialize() + extData,
dataType: 'json',
success: function (data) {
if (data !== null && typeof data === 'object') {
12 years ago
$.each(data.attributes, function () {
12 years ago
if (!this.enableAjaxValidation) {
12 years ago
delete data[this.name];
12 years ago
}
});
successCallback($.extend({}, messages, data));
} else {
successCallback(messages);
}
},
12 years ago
error: errorCallback
12 years ago
});
};
12 years ago
var validated = false;
12 years ago
var submitForm = function () {
12 years ago
var $form = $(this),
data = $form.data('yiiActiveForm');
12 years ago
if (validated) {
validated = false;
return true;
}
12 years ago
if (data.settings.timer !== undefined) {
clearTimeout(data.settings.timer);
12 years ago
}
12 years ago
data.submitting = true;
if (!data.settings.beforeValidate || data.settings.beforeValidate($form)) {
validateForm($form, function (messages) {
12 years ago
var hasError = false;
12 years ago
$.each(data.attributes, function () {
hasError = updateInput($form, this, messages) || hasError;
12 years ago
});
12 years ago
updateSummary($form, messages);
if (!data.settings.afterValidate || data.settings.afterValidate($form, data, hasError)) {
12 years ago
if (!hasError) {
validated = true;
12 years ago
var $button = data.submitObject || $form.find(':submit:first');
12 years ago
// TODO: if the submission is caused by "change" event, it will not work
if ($button.length) {
$button.click();
12 years ago
} else {
// no submit button in the form
12 years ago
$form.submit();
}
return;
}
}
12 years ago
data.submitting = false;
12 years ago
});
} else {
12 years ago
data.submitting = false;
12 years ago
}
return false;
};
12 years ago
var resetForm = function () {
12 years ago
var $form = $(this);
var data = $form.data('yiiActiveForm');
/**
12 years ago
* because we bind directly to a form reset event, not to a reset button (that could or could not exist),
* when this function is executed form elements values have not been reset yet,
* because of that we use the setTimeout
*/
setTimeout(function () {
12 years ago
$.each(data.attributes, function () {
12 years ago
this.status = 0;
12 years ago
$form.find(this.container).removeClass(
data.settings.validatingCssClass + ' ' +
data.settings.errorCssClass + ' ' +
data.settings.successCssClass
12 years ago
);
12 years ago
$form.find(this.error).html('');
12 years ago
/*
12 years ago
* without the setTimeout() we would get here the current entered value before the reset instead of the reset value
12 years ago
*/
12 years ago
this.value = getValue($form, this);
12 years ago
});
12 years ago
$form.find(data.settings.summary).hide().find('ul').html('');
}, 1);
12 years ago
};
/**
* updates the error message and the input container for a particular attribute.
* @param attribute object the configuration for a particular attribute.
* @param messages array the json data obtained from the ajax validation request
* @param $form the form jQuery object
12 years ago
* @return boolean whether there is a validation error for the specified attribute
*/
12 years ago
var updateInput = function ($form, attribute, messages) {
var data = $form.data('yiiActiveForm'),
$input = findInput($form, attribute),
hasError = false;
12 years ago
12 years ago
attribute.status = 1;
if ($input.length) {
12 years ago
hasError = messages && $.isArray(messages[attribute.name]) && messages[attribute.name].length;
12 years ago
var $container = $form.find(attribute.container);
12 years ago
$container.removeClass(
12 years ago
data.settings.validatingCssClass + ' ' +
data.settings.errorCssClass + ' ' +
data.settings.successCssClass
12 years ago
);
if (hasError) {
12 years ago
$container.find(attribute.error).html(messages[attribute.name][0]);
12 years ago
$container.addClass(data.settings.errorCssClass);
} else if (attribute.enableAjaxValidation || attribute.enableClientValidation && attribute.validate) {
$container.addClass(data.settings.successCssClass);
12 years ago
}
12 years ago
attribute.value = getValue($form, attribute);
12 years ago
}
return hasError;
};
12 years ago
var updateSummary = function ($form, messages) {
var data = $form.data('yiiActiveForm'),
12 years ago
$summary = $form.find(data.settings.errorSummary),
12 years ago
content = '';
12 years ago
if ($summary.length && messages) {
$.each(data.attributes, function () {
if ($.isArray(messages[this.name])) {
content += '<li>' + messages[this.name].join('</li><li>') + '</li>';
12 years ago
}
});
12 years ago
$summary.toggle(content !== '').find('ul').html(content);
12 years ago
}
12 years ago
};
12 years ago
})(window.jQuery);