ActiveForm.php 12 KB
Newer Older
Qiang Xue committed
1
<?php
Qiang Xue committed
2 3 4 5 6
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */
Qiang Xue committed
7

Qiang Xue committed
8 9
namespace yii\widgets;

Qiang Xue committed
10
use Yii;
Qiang Xue committed
11
use yii\base\Widget;
Qiang Xue committed
12
use yii\base\Model;
13
use yii\helpers\Url;
Qiang Xue committed
14
use yii\helpers\Html;
Qiang Xue committed
15
use yii\helpers\Json;
16
use yii\web\JsExpression;
Qiang Xue committed
17 18 19 20 21 22 23 24

/**
 * ActiveForm ...
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class ActiveForm extends Widget
Qiang Xue committed
25
{
Qiang Xue committed
26
	/**
Qiang Xue committed
27
	 * @param array|string $action the form action URL. This parameter will be processed by [[\yii\helpers\Html::url()]].
Qiang Xue committed
28 29 30 31 32 33 34
	 */
	public $action = '';
	/**
	 * @var string the form submission method. This should be either 'post' or 'get'.
	 * Defaults to 'post'.
	 */
	public $method = 'post';
Qiang Xue committed
35
	/**
Qiang Xue committed
36
	 * @var array the HTML attributes (name-value pairs) for the form tag.
37
	 * The values will be HTML-encoded using [[\yii\helpers\Html::encode()]].
Qiang Xue committed
38 39
	 * If a value is null, the corresponding attribute will not be rendered.
	 */
Alexander Makarov committed
40
	public $options = [];
Qiang Xue committed
41 42
	/**
	 * @var array the default configuration used by [[field()]] when creating a new field object.
Qiang Xue committed
43
	 */
44
	public $fieldConfig;
Qiang Xue committed
45
	/**
Qiang Xue committed
46 47
	 * @var string the default CSS class for the error summary container.
	 * @see errorSummary()
Qiang Xue committed
48
	 */
Qiang Xue committed
49
	public $errorSummaryCssClass = 'error-summary';
Qiang Xue committed
50 51 52 53 54 55 56
	/**
	 * @var string the CSS class that is added to a field container when the associated attribute is required.
	 */
	public $requiredCssClass = 'required';
	/**
	 * @var string the CSS class that is added to a field container when the associated attribute has validation error.
	 */
57
	public $errorCssClass = 'has-error';
Qiang Xue committed
58 59 60
	/**
	 * @var string the CSS class that is added to a field container when the associated attribute is successfully validated.
	 */
61
	public $successCssClass = 'has-success';
Qiang Xue committed
62 63 64 65
	/**
	 * @var string the CSS class that is added to a field container when the associated attribute is being validated.
	 */
	public $validatingCssClass = 'validating';
Qiang Xue committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
	/**
	 * @var boolean whether to enable client-side data validation.
	 * If [[ActiveField::enableClientValidation]] is set, its value will take precedence for that input field.
	 */
	public $enableClientValidation = true;
	/**
	 * @var boolean whether to enable AJAX-based data validation.
	 * If [[ActiveField::enableAjaxValidation]] is set, its value will take precedence for that input field.
	 */
	public $enableAjaxValidation = false;
	/**
	 * @var array|string the URL for performing AJAX-based validation. This property will be processed by
	 * [[Html::url()]]. Please refer to [[Html::url()]] for more details on how to configure this property.
	 * If this property is not set, it will take the value of the form's action attribute.
	 */
Qiang Xue committed
81
	public $validationUrl;
Qiang Xue committed
82 83 84 85 86 87 88 89
	/**
	 * @var boolean whether to perform validation when the form is submitted.
	 */
	public $validateOnSubmit = true;
	/**
	 * @var boolean whether to perform validation when an input field loses focus and its value is found changed.
	 * If [[ActiveField::validateOnChange]] is set, its value will take precedence for that input field.
	 */
Qiang Xue committed
90
	public $validateOnChange = true;
Qiang Xue committed
91 92 93 94 95 96 97
	/**
	 * @var boolean whether to perform validation while the user is typing in an input field.
	 * If [[ActiveField::validateOnType]] is set, its value will take precedence for that input field.
	 * @see validationDelay
	 */
	public $validateOnType = false;
	/**
Qiang Xue committed
98 99
	 * @var integer number of milliseconds that the validation should be delayed when an input field
	 * is changed or the user types in the field.
Qiang Xue committed
100 101 102
	 * If [[ActiveField::validationDelay]] is set, its value will take precedence for that input field.
	 */
	public $validationDelay = 200;
Qiang Xue committed
103 104 105
	/**
	 * @var string the name of the GET parameter indicating the validation request is an AJAX request.
	 */
106
	public $ajaxParam = 'ajax';
107 108 109 110
	/**
	 * @var string the type of data that you're expecting back from the server.
	 */
	public $ajaxDataType = 'json';
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
	/**
	 * @var string|JsExpression a JS callback that will be called when the form is being submitted.
	 * The signature of the callback should be:
	 *
	 * ~~~
	 * function ($form) {
	 *     ...return false to cancel submission...
	 * }
	 * ~~~
	 */
	public $beforeSubmit;
	/**
	 * @var string|JsExpression a JS callback that is called before validating an attribute.
	 * The signature of the callback should be:
	 *
	 * ~~~
	 * function ($form, attribute, messages) {
	 *     ...return false to cancel the validation...
	 * }
	 * ~~~
	 */
	public $beforeValidate;
	/**
	 * @var string|JsExpression a JS callback that is called after validating an attribute.
	 * The signature of the callback should be:
	 *
	 * ~~~
	 * function ($form, attribute, messages) {
	 * }
	 * ~~~
	 */
	public $afterValidate;
Qiang Xue committed
143
	/**
Qiang Xue committed
144
	 * @var array the client validation options for individual attributes. Each element of the array
Qiang Xue committed
145 146 147
	 * represents the validation options for a particular attribute.
	 * @internal
	 */
Alexander Makarov committed
148
	public $attributes = [];
Qiang Xue committed
149

Qiang Xue committed
150 151 152 153 154 155
	/**
	 * Initializes the widget.
	 * This renders the form open tag.
	 */
	public function init()
	{
Qiang Xue committed
156 157 158
		if (!isset($this->options['id'])) {
			$this->options['id'] = $this->getId();
		}
159
		if (!isset($this->fieldConfig['class'])) {
Qiang Xue committed
160
			$this->fieldConfig['class'] = ActiveField::className();
161
		}
Qiang Xue committed
162 163 164 165 166 167 168 169 170
		echo Html::beginForm($this->action, $this->method, $this->options);
	}

	/**
	 * Runs the widget.
	 * This registers the necessary javascript code and renders the form close tag.
	 */
	public function run()
	{
171
		if (!empty($this->attributes)) {
Qiang Xue committed
172 173 174
			$id = $this->options['id'];
			$options = Json::encode($this->getClientOptions());
			$attributes = Json::encode($this->attributes);
175 176 177
			$view = $this->getView();
			ActiveFormAsset::register($view);
			$view->registerJs("jQuery('#$id').yiiActiveForm($attributes, $options);");
Qiang Xue committed
178 179 180 181
		}
		echo Html::endForm();
	}

Qiang Xue committed
182 183 184 185
	/**
	 * Returns the options for the form JS widget.
	 * @return array the options
	 */
Qiang Xue committed
186 187
	protected function getClientOptions()
	{
Alexander Makarov committed
188
		$options = [
Qiang Xue committed
189 190
			'errorSummary' => '.' . $this->errorSummaryCssClass,
			'validateOnSubmit' => $this->validateOnSubmit,
Qiang Xue committed
191 192 193
			'errorCssClass' => $this->errorCssClass,
			'successCssClass' => $this->successCssClass,
			'validatingCssClass' => $this->validatingCssClass,
194
			'ajaxParam' => $this->ajaxParam,
195
			'ajaxDataType' => $this->ajaxDataType,
Alexander Makarov committed
196
		];
Qiang Xue committed
197
		if ($this->validationUrl !== null) {
198
			$options['validationUrl'] = Url::to($this->validationUrl);
Qiang Xue committed
199
		}
Alexander Makarov committed
200
		foreach (['beforeSubmit', 'beforeValidate', 'afterValidate'] as $name) {
201 202 203 204
			if (($value = $this->$name) !== null) {
				$options[$name] = $value instanceof JsExpression ? $value : new JsExpression($value);
			}
		}
Qiang Xue committed
205
		return $options;
Qiang Xue committed
206 207
	}

Qiang Xue committed
208
	/**
Qiang Xue committed
209 210 211 212 213 214 215 216 217
	 * Generates a summary of the validation errors.
	 * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
	 * @param Model|Model[] $models the model(s) associated with this form
	 * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
	 *
	 * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
	 * - footer: string, the footer HTML for the error summary.
	 *
	 * The rest of the options will be rendered as the attributes of the container tag. The values will
218
	 * be HTML-encoded using [[\yii\helpers\Html::encode()]]. If a value is null, the corresponding attribute will not be rendered.
Qiang Xue committed
219
	 * @return string the generated error summary
Qiang Xue committed
220
	 */
Alexander Makarov committed
221
	public function errorSummary($models, $options = [])
Qiang Xue committed
222
	{
Alexander Makarov committed
223 224 225
		if (!is_array($models)) {
			$models = [$models];
		}
Qiang Xue committed
226

Alexander Makarov committed
227
		$lines = [];
Qiang Xue committed
228
		foreach ($models as $model) {
slavcodev committed
229
			/** @var Model $model */
Qiang Xue committed
230 231
			foreach ($model->getFirstErrors() as $error) {
				$lines[] = Html::encode($error);
Qiang Xue committed
232 233 234
			}
		}

235
		$header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
Qiang Xue committed
236
		$footer = isset($options['footer']) ? $options['footer'] : '';
Qiang Xue committed
237
		unset($options['header'], $options['footer']);
Qiang Xue committed
238 239

		if (!isset($options['class'])) {
Qiang Xue committed
240
			$options['class'] = $this->errorSummaryCssClass;
Qiang Xue committed
241
		} else {
Qiang Xue committed
242
			$options['class'] .= ' ' . $this->errorSummaryCssClass;
Qiang Xue committed
243 244
		}

245
		if (!empty($lines)) {
246
			$content = "<ul><li>" . implode("</li>\n<li>", $lines) . "</li></ul>";
Qiang Xue committed
247
			return Html::tag('div', $header . $content . $footer, $options);
Qiang Xue committed
248 249 250
		} else {
			$content = "<ul></ul>";
			$options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
Qiang Xue committed
251
			return Html::tag('div', $header . $content . $footer, $options);
Qiang Xue committed
252
		}
Qiang Xue committed
253 254
	}

Qiang Xue committed
255
	/**
256
	 * Generates a form field.
Qiang Xue committed
257
	 * A form field is associated with a model and an attribute. It contains a label, an input and an error message
258
	 * and use them to interact with end users to collect their inputs for the attribute.
Qiang Xue committed
259 260 261
	 * @param Model $model the data model
	 * @param string $attribute the attribute name or expression. See [[Html::getAttributeName()]] for the format
	 * about attribute expression.
Qiang Xue committed
262
	 * @param array $options the additional configurations for the field object
Qiang Xue committed
263
	 * @return ActiveField the created ActiveField object
Qiang Xue committed
264
	 * @see fieldConfig
Qiang Xue committed
265
	 */
Alexander Makarov committed
266
	public function field($model, $attribute, $options = [])
Qiang Xue committed
267
	{
Alexander Makarov committed
268
		return Yii::createObject(array_merge($this->fieldConfig, $options, [
Qiang Xue committed
269 270 271
			'model' => $model,
			'attribute' => $attribute,
			'form' => $this,
Alexander Makarov committed
272
		]));
Qiang Xue committed
273
	}
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362

	/**
	 * Validates one or several models and returns an error message array indexed by the attribute IDs.
	 * This is a helper method that simplifies the way of writing AJAX validation code.
	 *
	 * For example, you may use the following code in a controller action to respond
	 * to an AJAX validation request:
	 *
	 * ~~~
	 * $model = new Post;
	 * $model->load($_POST);
	 * if (Yii::$app->request->isAjax) {
	 *     Yii::$app->response->format = Response::FORMAT_JSON;
	 *     return ActiveForm::validate($model);
	 * }
	 * // ... respond to non-AJAX request ...
	 * ~~~
	 *
	 * To validate multiple models, simply pass each model as a parameter to this method, like
	 * the following:
	 *
	 * ~~~
	 * ActiveForm::validate($model1, $model2, ...);
	 * ~~~
	 *
	 * @param Model $model the model to be validated
	 * @param mixed $attributes list of attributes that should be validated.
	 * If this parameter is empty, it means any attribute listed in the applicable
	 * validation rules should be validated.
	 *
	 * When this method is used to validate multiple models, this parameter will be interpreted
	 * as a model.
	 *
	 * @return array the error message array indexed by the attribute IDs.
	 */
	public static function validate($model, $attributes = null)
	{
		$result = [];
		if ($attributes instanceof Model) {
			// validating multiple models
			$models = func_get_args();
			$attributes = null;
		} else {
			$models = [$model];
		}
		/** @var Model $model */
		foreach ($models as $model) {
			$model->validate($attributes);
			foreach ($model->getErrors() as $attribute => $errors) {
				$result[Html::getInputId($model, $attribute)] = $errors;
			}
		}
		return $result;
	}

	/**
	 * Validates an array of model instances and returns an error message array indexed by the attribute IDs.
	 * This is a helper method that simplifies the way of writing AJAX validation code for tabular input.
	 *
	 * For example, you may use the following code in a controller action to respond
	 * to an AJAX validation request:
	 *
	 * ~~~
	 * // ... load $models ...
	 * if (Yii::$app->request->isAjax) {
	 *     Yii::$app->response->format = Response::FORMAT_JSON;
	 *     return ActiveForm::validateMultiple($models);
	 * }
	 * // ... respond to non-AJAX request ...
	 * ~~~
	 *
	 * @param array $models an array of models to be validated.
	 * @param mixed $attributes list of attributes that should be validated.
	 * If this parameter is empty, it means any attribute listed in the applicable
	 * validation rules should be validated.
	 * @return array the error message array indexed by the attribute IDs.
	 */
	public static function validateMultiple($models, $attributes = null)
	{
		$result = [];
		/** @var Model $model */
		foreach ($models as $i => $model) {
			$model->validate($attributes);
			foreach ($model->getErrors() as $attribute => $errors) {
				$result[Html::getInputId($model, "[$i]" . $attribute)] = $errors;
			}
		}
		return $result;
	}
Qiang Xue committed
363
}