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

8
namespace yii\helpers;
Qiang Xue committed
9 10 11

use Yii;
use yii\base\InvalidParamException;
12
use yii\db\ActiveRecordInterface;
13
use yii\web\Request;
Qiang Xue committed
14
use yii\base\Model;
Qiang Xue committed
15 16

/**
17
 * BaseHtml provides concrete implementation for [[Html]].
18
 *
19
 * Do not use BaseHtml. Use [[Html]] instead.
Qiang Xue committed
20 21 22 23
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
24
class BaseHtml
Qiang Xue committed
25 26 27 28 29
{
	/**
	 * @var array list of void elements (element name => 1)
	 * @see http://www.w3.org/TR/html-markup/syntax.html#void-element
	 */
Alexander Makarov committed
30
	public static $voidElements = [
Qiang Xue committed
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
		'area' => 1,
		'base' => 1,
		'br' => 1,
		'col' => 1,
		'command' => 1,
		'embed' => 1,
		'hr' => 1,
		'img' => 1,
		'input' => 1,
		'keygen' => 1,
		'link' => 1,
		'meta' => 1,
		'param' => 1,
		'source' => 1,
		'track' => 1,
		'wbr' => 1,
Alexander Makarov committed
47
	];
Qiang Xue committed
48 49
	/**
	 * @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes
resurtm committed
50
	 * that are rendered by [[renderTagAttributes()]].
Qiang Xue committed
51
	 */
Alexander Makarov committed
52
	public static $attributeOrder = [
Qiang Xue committed
53 54
		'type',
		'id',
Qiang Xue committed
55
		'class',
Qiang Xue committed
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
		'name',
		'value',

		'href',
		'src',
		'action',
		'method',

		'selected',
		'checked',
		'readonly',
		'disabled',
		'multiple',

		'size',
		'maxlength',
		'width',
		'height',
		'rows',
		'cols',

		'alt',
		'title',
		'rel',
		'media',
Alexander Makarov committed
81
	];
Qiang Xue committed
82

83

Qiang Xue committed
84 85
	/**
	 * Encodes special characters into HTML entities.
86
	 * The [[\yii\base\Application::charset|application charset]] will be used for encoding.
Qiang Xue committed
87
	 * @param string $content the content to be encoded
Qiang Xue committed
88 89
	 * @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false,
	 * HTML entities in `$content` will not be further encoded.
Qiang Xue committed
90
	 * @return string the encoded content
91
	 * @see decode()
Qiang Xue committed
92 93
	 * @see http://www.php.net/manual/en/function.htmlspecialchars.php
	 */
Qiang Xue committed
94
	public static function encode($content, $doubleEncode = true)
Qiang Xue committed
95
	{
Qiang Xue committed
96
		return htmlspecialchars($content, ENT_QUOTES, Yii::$app->charset, $doubleEncode);
Qiang Xue committed
97 98 99 100 101 102 103
	}

	/**
	 * Decodes special HTML entities back to the corresponding characters.
	 * This is the opposite of [[encode()]].
	 * @param string $content the content to be decoded
	 * @return string the decoded content
104
	 * @see encode()
Qiang Xue committed
105 106 107 108 109 110 111 112 113 114 115 116
	 * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
	 */
	public static function decode($content)
	{
		return htmlspecialchars_decode($content, ENT_QUOTES);
	}

	/**
	 * Generates a complete HTML tag.
	 * @param string $name the tag name
	 * @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded.
	 * If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks.
117 118
	 * @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs.
	 * These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
Qiang Xue committed
119
	 * If a value is null, the corresponding attribute will not be rendered.
120 121 122
	 *
	 * For example when using `['class' => 'my-class', 'target' => '_blank', 'value' => null]` it will result in the
	 * html attributes rendered like this: `class="my-class" target="_blank"`.
123
	 *
124
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
125
	 *
Qiang Xue committed
126
	 * @return string the generated HTML tag
127 128
	 * @see beginTag()
	 * @see endTag()
Qiang Xue committed
129
	 */
Alexander Makarov committed
130
	public static function tag($name, $content = '', $options = [])
Qiang Xue committed
131
	{
Alexander Kochetov committed
132 133
		$html = "<$name" . static::renderTagAttributes($options) . '>';
		return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>";
Qiang Xue committed
134 135 136 137 138 139 140 141
	}

	/**
	 * Generates a start tag.
	 * @param string $name the tag name
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
142
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
143
	 * @return string the generated start tag
144 145
	 * @see endTag()
	 * @see tag()
Qiang Xue committed
146
	 */
Alexander Makarov committed
147
	public static function beginTag($name, $options = [])
Qiang Xue committed
148
	{
149
		return "<$name" . static::renderTagAttributes($options) . '>';
Qiang Xue committed
150 151 152 153 154 155
	}

	/**
	 * Generates an end tag.
	 * @param string $name the tag name
	 * @return string the generated end tag
156 157
	 * @see beginTag()
	 * @see tag()
Qiang Xue committed
158 159 160 161 162 163 164 165 166 167 168 169 170
	 */
	public static function endTag($name)
	{
		return "</$name>";
	}

	/**
	 * Generates a style tag.
	 * @param string $content the style content
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
	 * If the options does not contain "type", a "type" attribute with value "text/css" will be used.
171
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
172 173
	 * @return string the generated style tag
	 */
Alexander Makarov committed
174
	public static function style($content, $options = [])
Qiang Xue committed
175
	{
176
		return static::tag('style', $content, $options);
Qiang Xue committed
177 178 179 180 181 182 183 184 185
	}

	/**
	 * Generates a script tag.
	 * @param string $content the script content
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
	 * If the options does not contain "type", a "type" attribute with value "text/javascript" will be rendered.
186
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
187 188
	 * @return string the generated script tag
	 */
Alexander Makarov committed
189
	public static function script($content, $options = [])
Qiang Xue committed
190
	{
191
		return static::tag('script', $content, $options);
Qiang Xue committed
192 193 194 195
	}

	/**
	 * Generates a link tag that refers to an external CSS file.
Alexander Makarov committed
196
	 * @param array|string $url the URL of the external CSS file. This parameter will be processed by [[\yii\helpers\Url::to()]].
Qiang Xue committed
197 198 199
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
200
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
201
	 * @return string the generated link tag
Alexander Makarov committed
202
	 * @see \yii\helpers\Url::to()
Qiang Xue committed
203
	 */
Alexander Makarov committed
204
	public static function cssFile($url, $options = [])
Qiang Xue committed
205
	{
206 207 208
		if (!isset($options['rel'])) {
			$options['rel'] = 'stylesheet';
		}
209
		$options['href'] = Url::to($url);
Qiang Xue committed
210 211 212 213 214
		return static::tag('link', '', $options);
	}

	/**
	 * Generates a script tag that refers to an external JavaScript file.
Alexander Makarov committed
215
	 * @param string $url the URL of the external JavaScript file. This parameter will be processed by [[\yii\helpers\Url::to()]].
Qiang Xue committed
216 217 218
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
219
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
220
	 * @return string the generated script tag
Alexander Makarov committed
221
	 * @see \yii\helpers\Url::to()
Qiang Xue committed
222
	 */
Alexander Makarov committed
223
	public static function jsFile($url, $options = [])
Qiang Xue committed
224
	{
225
		$options['src'] = Url::to($url);
Qiang Xue committed
226 227 228 229 230
		return static::tag('script', '', $options);
	}

	/**
	 * Generates a form start tag.
Alexander Makarov committed
231
	 * @param array|string $action the form action URL. This parameter will be processed by [[\yii\helpers\Url::to()]].
232 233 234
	 * @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive).
	 * Since most browsers only support "post" and "get", if other methods are given, they will
	 * be simulated using "post", and a hidden input will be added which contains the actual method type.
235
	 * See [[\yii\web\Request::methodParam]] for more details.
Qiang Xue committed
236 237 238
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
239
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
240
	 * @return string the generated form start tag.
241
	 * @see endForm()
Qiang Xue committed
242
	 */
Alexander Makarov committed
243
	public static function beginForm($action = '', $method = 'post', $options = [])
Qiang Xue committed
244
	{
245
		$action = Url::to($action);
Qiang Xue committed
246

Alexander Makarov committed
247
		$hiddenInputs = [];
248

Qiang Xue committed
249 250 251 252
		$request = Yii::$app->getRequest();
		if ($request instanceof Request) {
			if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) {
				// simulate PUT, DELETE, etc. via POST
253
				$hiddenInputs[] = static::hiddenInput($request->methodParam, $method);
254 255
				$method = 'post';
			}
Qiang Xue committed
256
			if ($request->enableCsrfValidation && !strcasecmp($method, 'post')) {
257
				$hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken());
Qiang Xue committed
258
			}
259 260
		}

Qiang Xue committed
261
		if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) {
262 263
			// query parameters in the action are ignored for GET method
			// we use hidden fields to add them back
Qiang Xue committed
264 265
			foreach (explode('&', substr($action, $pos + 1)) as $pair) {
				if (($pos1 = strpos($pair, '=')) !== false) {
266 267 268 269
					$hiddenInputs[] = static::hiddenInput(
						urldecode(substr($pair, 0, $pos1)),
						urldecode(substr($pair, $pos1 + 1))
					);
Qiang Xue committed
270
				} else {
271
					$hiddenInputs[] = static::hiddenInput(urldecode($pair), '');
Qiang Xue committed
272 273 274 275 276 277 278 279
				}
			}
			$action = substr($action, 0, $pos);
		}

		$options['action'] = $action;
		$options['method'] = $method;
		$form = static::beginTag('form', $options);
280
		if (!empty($hiddenInputs)) {
281
			$form .= "\n" . implode("\n", $hiddenInputs);
Qiang Xue committed
282 283 284 285 286 287 288 289
		}

		return $form;
	}

	/**
	 * Generates a form end tag.
	 * @return string the generated tag
290
	 * @see beginForm()
Qiang Xue committed
291 292 293 294 295 296 297 298 299
	 */
	public static function endForm()
	{
		return '</form>';
	}

	/**
	 * Generates a hyperlink tag.
	 * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
Carsten Brandt committed
300
	 * such as an image tag. If this is coming from end users, you should consider [[encode()]]
Qiang Xue committed
301
	 * it to prevent XSS attacks.
Alexander Makarov committed
302
	 * @param array|string|null $url the URL for the hyperlink tag. This parameter will be processed by [[yii\helpers\Url::to()]]
Qiang Xue committed
303 304 305 306 307
	 * and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute
	 * will not be generated.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
308
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
309
	 * @return string the generated hyperlink
Alexander Makarov committed
310
	 * @see yii\helpers\Url::to()
Qiang Xue committed
311
	 */
Alexander Makarov committed
312
	public static function a($text, $url = null, $options = [])
Qiang Xue committed
313 314
	{
		if ($url !== null) {
315
			$options['href'] = Url::to($url);
Qiang Xue committed
316 317 318 319 320 321 322
		}
		return static::tag('a', $text, $options);
	}

	/**
	 * Generates a mailto hyperlink.
	 * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
Carsten Brandt committed
323
	 * such as an image tag. If this is coming from end users, you should consider [[encode()]]
Qiang Xue committed
324 325 326 327 328 329
	 * it to prevent XSS attacks.
	 * @param string $email email address. If this is null, the first parameter (link body) will be treated
	 * as the email address and used.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
330
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
331 332
	 * @return string the generated mailto link
	 */
Alexander Makarov committed
333
	public static function mailto($text, $email = null, $options = [])
Qiang Xue committed
334
	{
Qiang Xue committed
335 336
		$options['href'] = 'mailto:' . ($email === null ? $text : $email);
		return static::tag('a', $text, $options);
Qiang Xue committed
337 338 339 340
	}

	/**
	 * Generates an image tag.
341
	 * @param string $src the image URL. This parameter will be processed by [[yii\helpers\Url::to()]].
Qiang Xue committed
342 343 344
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
345
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
346 347
	 * @return string the generated image tag
	 */
Alexander Makarov committed
348
	public static function img($src, $options = [])
Qiang Xue committed
349
	{
350
		$options['src'] = Url::to($src);
Qiang Xue committed
351 352 353
		if (!isset($options['alt'])) {
			$options['alt'] = '';
		}
354
		return static::tag('img', '', $options);
Qiang Xue committed
355 356 357 358 359
	}

	/**
	 * Generates a label tag.
	 * @param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code
Qiang Xue committed
360
	 * such as an image tag. If this is is coming from end users, you should [[encode()]]
Qiang Xue committed
361 362 363 364 365 366
	 * it to prevent XSS attacks.
	 * @param string $for the ID of the HTML element that this label is associated with.
	 * If this is null, the "for" attribute will not be generated.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
367
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
368 369
	 * @return string the generated label tag
	 */
Alexander Makarov committed
370
	public static function label($content, $for = null, $options = [])
Qiang Xue committed
371 372 373 374 375 376 377 378 379 380 381 382 383
	{
		$options['for'] = $for;
		return static::tag('label', $content, $options);
	}

	/**
	 * Generates a button tag.
	 * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
	 * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
	 * you should consider [[encode()]] it to prevent XSS attacks.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
384
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
385 386
	 * @return string the generated button tag
	 */
Alexander Makarov committed
387
	public static function button($content = 'Button', $options = [])
Qiang Xue committed
388 389 390 391 392 393 394 395 396 397 398 399
	{
		return static::tag('button', $content, $options);
	}

	/**
	 * Generates a submit button tag.
	 * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
	 * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
	 * you should consider [[encode()]] it to prevent XSS attacks.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
400
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
401 402
	 * @return string the generated submit button tag
	 */
Alexander Makarov committed
403
	public static function submitButton($content = 'Submit', $options = [])
Qiang Xue committed
404 405
	{
		$options['type'] = 'submit';
Qiang Xue committed
406
		return static::button($content, $options);
Qiang Xue committed
407 408 409 410 411 412 413 414 415 416
	}

	/**
	 * Generates a reset button tag.
	 * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
	 * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
	 * you should consider [[encode()]] it to prevent XSS attacks.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
417
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
418 419
	 * @return string the generated reset button tag
	 */
Alexander Makarov committed
420
	public static function resetButton($content = 'Reset', $options = [])
Qiang Xue committed
421 422
	{
		$options['type'] = 'reset';
Qiang Xue committed
423
		return static::button($content, $options);
Qiang Xue committed
424 425 426 427 428 429 430 431 432 433
	}

	/**
	 * Generates an input type of the given type.
	 * @param string $type the type attribute.
	 * @param string $name the name attribute. If it is null, the name attribute will not be generated.
	 * @param string $value the value attribute. If it is null, the value attribute will not be generated.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
434
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
435 436
	 * @return string the generated input tag
	 */
Alexander Makarov committed
437
	public static function input($type, $name = null, $value = null, $options = [])
Qiang Xue committed
438 439 440
	{
		$options['type'] = $type;
		$options['name'] = $name;
441
		$options['value'] = $value === null ? null : (string)$value;
442
		return static::tag('input', '', $options);
Qiang Xue committed
443 444 445 446
	}

	/**
	 * Generates an input button.
Qiang Xue committed
447
	 * @param string $label the value attribute. If it is null, the value attribute will not be generated.
Qiang Xue committed
448 449 450
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
451
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
452 453
	 * @return string the generated button tag
	 */
Alexander Makarov committed
454
	public static function buttonInput($label = 'Button', $options = [])
Qiang Xue committed
455
	{
Qiang Xue committed
456 457
		$options['type'] = 'button';
		$options['value'] = $label;
458
		return static::tag('input', '', $options);
Qiang Xue committed
459 460 461 462
	}

	/**
	 * Generates a submit input button.
Qiang Xue committed
463
	 * @param string $label the value attribute. If it is null, the value attribute will not be generated.
Qiang Xue committed
464 465 466
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
467
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
468 469
	 * @return string the generated button tag
	 */
Alexander Makarov committed
470
	public static function submitInput($label = 'Submit', $options = [])
Qiang Xue committed
471
	{
Qiang Xue committed
472 473
		$options['type'] = 'submit';
		$options['value'] = $label;
474
		return static::tag('input', '', $options);
Qiang Xue committed
475 476 477 478
	}

	/**
	 * Generates a reset input button.
Qiang Xue committed
479
	 * @param string $label the value attribute. If it is null, the value attribute will not be generated.
Qiang Xue committed
480 481
	 * @param array $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]].
	 * Attributes whose value is null will be ignored and not put in the tag returned.
482
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
483 484
	 * @return string the generated button tag
	 */
Alexander Makarov committed
485
	public static function resetInput($label = 'Reset', $options = [])
Qiang Xue committed
486
	{
Qiang Xue committed
487 488
		$options['type'] = 'reset';
		$options['value'] = $label;
489
		return static::tag('input', '', $options);
Qiang Xue committed
490 491 492 493 494 495 496 497 498
	}

	/**
	 * Generates a text input field.
	 * @param string $name the name attribute.
	 * @param string $value the value attribute. If it is null, the value attribute will not be generated.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
499
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
500 501
	 * @return string the generated button tag
	 */
Alexander Makarov committed
502
	public static function textInput($name, $value = null, $options = [])
Qiang Xue committed
503 504 505 506 507 508 509 510 511 512 513
	{
		return static::input('text', $name, $value, $options);
	}

	/**
	 * Generates a hidden input field.
	 * @param string $name the name attribute.
	 * @param string $value the value attribute. If it is null, the value attribute will not be generated.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
514
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
515 516
	 * @return string the generated button tag
	 */
Alexander Makarov committed
517
	public static function hiddenInput($name, $value = null, $options = [])
Qiang Xue committed
518 519 520 521 522 523 524 525 526 527 528
	{
		return static::input('hidden', $name, $value, $options);
	}

	/**
	 * Generates a password input field.
	 * @param string $name the name attribute.
	 * @param string $value the value attribute. If it is null, the value attribute will not be generated.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
529
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
530 531
	 * @return string the generated button tag
	 */
Alexander Makarov committed
532
	public static function passwordInput($name, $value = null, $options = [])
Qiang Xue committed
533 534 535 536 537 538 539 540 541 542 543 544 545 546
	{
		return static::input('password', $name, $value, $options);
	}

	/**
	 * Generates a file input field.
	 * To use a file input field, you should set the enclosing form's "enctype" attribute to
	 * be "multipart/form-data". After the form is submitted, the uploaded file information
	 * can be obtained via $_FILES[$name] (see PHP documentation).
	 * @param string $name the name attribute.
	 * @param string $value the value attribute. If it is null, the value attribute will not be generated.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
547
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
548 549
	 * @return string the generated button tag
	 */
Alexander Makarov committed
550
	public static function fileInput($name, $value = null, $options = [])
Qiang Xue committed
551 552 553 554 555 556 557 558 559 560 561
	{
		return static::input('file', $name, $value, $options);
	}

	/**
	 * Generates a text area input.
	 * @param string $name the input name
	 * @param string $value the input value. Note that it will be encoded using [[encode()]].
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
562
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
563 564
	 * @return string the generated text area tag
	 */
Alexander Makarov committed
565
	public static function textarea($name, $value = '', $options = [])
Qiang Xue committed
566 567 568 569 570 571 572 573 574
	{
		$options['name'] = $name;
		return static::tag('textarea', static::encode($value), $options);
	}

	/**
	 * Generates a radio button input.
	 * @param string $name the name attribute.
	 * @param boolean $checked whether the radio button should be checked.
Qiang Xue committed
575
	 * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
Qiang Xue committed
576 577 578 579
	 *
	 * - uncheck: string, the value associated with the uncheck state of the radio button. When this attribute
	 *   is present, a hidden input will be generated so that if the radio button is not checked and is submitted,
	 *   the value of this attribute will still be submitted to the server via the hidden input.
580 581 582 583
	 * - label: string, a label displayed next to the radio button.  It will NOT be HTML-encoded. Therefore you can pass
	 *   in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
	 *   When this option is specified, the radio button will be enclosed by a label tag.
	 * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
584 585 586
	 * - container: array|boolean, the HTML attributes for the container tag. This is only used when the "label" option is specified.
	 *   If it is false, no container will be rendered. If it is an array or not, a "div" container will be rendered
	 *   around the the radio button.
Qiang Xue committed
587
	 *
588
	 * The rest of the options will be rendered as the attributes of the resulting radio button tag. The values will
Qiang Xue committed
589
	 * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
590
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
591 592 593
	 *
	 * @return string the generated radio button tag
	 */
Alexander Makarov committed
594
	public static function radio($name, $checked = false, $options = [])
Qiang Xue committed
595
	{
Qiang Xue committed
596
		$options['checked'] = (boolean)$checked;
597
		$value = array_key_exists('value', $options) ? $options['value'] : '1';
Qiang Xue committed
598 599 600 601 602 603 604
		if (isset($options['uncheck'])) {
			// add a hidden field so that if the radio button is not selected, it still submits a value
			$hidden = static::hiddenInput($name, $options['uncheck']);
			unset($options['uncheck']);
		} else {
			$hidden = '';
		}
605 606
		if (isset($options['label'])) {
			$label = $options['label'];
Alexander Makarov committed
607
			$labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
608 609
			$container = isset($options['container']) ? $options['container'] : ['class' => 'radio'];
			unset($options['label'], $options['labelOptions'], $options['container']);
610
			$content = static::label(static::input('radio', $name, $value, $options) . ' ' . $label, null, $labelOptions);
611 612 613 614 615
			if (is_array($container)) {
				return $hidden . static::tag('div', $content, $container);
			} else {
				return $hidden . $content;
			}
616 617 618
		} else {
			return $hidden . static::input('radio', $name, $value, $options);
		}
Qiang Xue committed
619 620 621 622 623 624
	}

	/**
	 * Generates a checkbox input.
	 * @param string $name the name attribute.
	 * @param boolean $checked whether the checkbox should be checked.
Qiang Xue committed
625
	 * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
Qiang Xue committed
626 627 628 629
	 *
	 * - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute
	 *   is present, a hidden input will be generated so that if the checkbox is not checked and is submitted,
	 *   the value of this attribute will still be submitted to the server via the hidden input.
630 631 632 633
	 * - label: string, a label displayed next to the checkbox.  It will NOT be HTML-encoded. Therefore you can pass
	 *   in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
	 *   When this option is specified, the checkbox will be enclosed by a label tag.
	 * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
634 635 636
	 * - container: array|boolean, the HTML attributes for the container tag. This is only used when the "label" option is specified.
	 *   If it is false, no container will be rendered. If it is an array or not, a "div" container will be rendered
	 *   around the the radio button.
Qiang Xue committed
637
	 *
638
	 * The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will
Qiang Xue committed
639
	 * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
640
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
641 642 643
	 *
	 * @return string the generated checkbox tag
	 */
Alexander Makarov committed
644
	public static function checkbox($name, $checked = false, $options = [])
Qiang Xue committed
645
	{
Qiang Xue committed
646
		$options['checked'] = (boolean)$checked;
647
		$value = array_key_exists('value', $options) ? $options['value'] : '1';
Qiang Xue committed
648 649 650 651 652 653 654
		if (isset($options['uncheck'])) {
			// add a hidden field so that if the checkbox is not selected, it still submits a value
			$hidden = static::hiddenInput($name, $options['uncheck']);
			unset($options['uncheck']);
		} else {
			$hidden = '';
		}
655 656
		if (isset($options['label'])) {
			$label = $options['label'];
Alexander Makarov committed
657
			$labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
658 659
			$container = isset($options['container']) ? $options['container'] : ['class' => 'checkbox'];
			unset($options['label'], $options['labelOptions'], $options['container']);
660
			$content = static::label(static::input('checkbox', $name, $value, $options) . ' ' . $label, null, $labelOptions);
661 662 663 664 665
			if (is_array($container)) {
				return $hidden . static::tag('div', $content, $container);
			} else {
				return $hidden . $content;
			}
666 667 668
		} else {
			return $hidden . static::input('checkbox', $name, $value, $options);
		}
Qiang Xue committed
669 670 671 672 673 674 675 676 677 678 679 680 681 682
	}

	/**
	 * Generates a drop-down list.
	 * @param string $name the input name
	 * @param string $selection the selected value
	 * @param array $items the option data items. The array keys are option values, and the array values
	 * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
	 * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
	 * If you have a list of data models, you may convert them into the format described above using
	 * [[\yii\helpers\ArrayHelper::map()]].
	 *
	 * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
	 * the labels will also be HTML-encoded.
Qiang Xue committed
683
	 * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
Qiang Xue committed
684 685 686 687 688
	 *
	 * - prompt: string, a prompt text to be displayed as the first option;
	 * - options: array, the attributes for the select option tags. The array keys must be valid option values,
	 *   and the array values are the extra attributes for the corresponding option tags. For example,
	 *
689 690 691 692 693 694
	 *   ~~~
	 *   [
	 *       'value1' => ['disabled' => true],
	 *       'value2' => ['label' => 'value 2'],
	 *   ];
	 *   ~~~
Qiang Xue committed
695 696 697 698
	 *
	 * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
	 *   except that the array keys represent the optgroup labels specified in $items.
	 *
699
	 * The rest of the options will be rendered as the attributes of the resulting tag. The values will
Qiang Xue committed
700
	 * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
701
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
702
	 *
Qiang Xue committed
703 704
	 * @return string the generated drop-down list tag
	 */
Alexander Makarov committed
705
	public static function dropDownList($name, $selection = null, $items = [], $options = [])
Qiang Xue committed
706
	{
Qiang Xue committed
707 708 709
		if (!empty($options['multiple'])) {
			return static::listBox($name, $selection, $items, $options);
		}
Qiang Xue committed
710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726
		$options['name'] = $name;
		$selectOptions = static::renderSelectOptions($selection, $items, $options);
		return static::tag('select', "\n" . $selectOptions . "\n", $options);
	}

	/**
	 * Generates a list box.
	 * @param string $name the input name
	 * @param string|array $selection the selected value(s)
	 * @param array $items the option data items. The array keys are option values, and the array values
	 * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
	 * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
	 * If you have a list of data models, you may convert them into the format described above using
	 * [[\yii\helpers\ArrayHelper::map()]].
	 *
	 * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
	 * the labels will also be HTML-encoded.
Qiang Xue committed
727
	 * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
Qiang Xue committed
728 729 730 731 732
	 *
	 * - prompt: string, a prompt text to be displayed as the first option;
	 * - options: array, the attributes for the select option tags. The array keys must be valid option values,
	 *   and the array values are the extra attributes for the corresponding option tags. For example,
	 *
733 734 735 736 737 738
	 *   ~~~
	 *   [
	 *       'value1' => ['disabled' => true],
	 *       'value2' => ['label' => 'value 2'],
	 *   ];
	 *   ~~~
Qiang Xue committed
739 740 741 742 743 744 745
	 *
	 * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
	 *   except that the array keys represent the optgroup labels specified in $items.
	 * - unselect: string, the value that will be submitted when no option is selected.
	 *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
	 *   mode, we can still obtain the posted unselect value.
	 *
746
	 * The rest of the options will be rendered as the attributes of the resulting tag. The values will
Qiang Xue committed
747
	 * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
748
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
749
	 *
Qiang Xue committed
750 751
	 * @return string the generated list box tag
	 */
Alexander Makarov committed
752
	public static function listBox($name, $selection = null, $items = [], $options = [])
Qiang Xue committed
753
	{
754
		if (!array_key_exists('size', $options)) {
755 756
			$options['size'] = 4;
		}
Alexander Makarov committed
757
		if (!empty($options['multiple']) && substr($name, -2) !== '[]') {
Qiang Xue committed
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
			$name .= '[]';
		}
		$options['name'] = $name;
		if (isset($options['unselect'])) {
			// add a hidden field so that if the list box has no option being selected, it still submits a value
			if (substr($name, -2) === '[]') {
				$name = substr($name, 0, -2);
			}
			$hidden = static::hiddenInput($name, $options['unselect']);
			unset($options['unselect']);
		} else {
			$hidden = '';
		}
		$selectOptions = static::renderSelectOptions($selection, $items, $options);
		return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
	}

	/**
	 * Generates a list of checkboxes.
	 * A checkbox list allows multiple selection, like [[listBox()]].
	 * As a result, the corresponding submitted value is an array.
	 * @param string $name the name attribute of each checkbox.
	 * @param string|array $selection the selected value(s).
	 * @param array $items the data item used to generate the checkboxes.
782
	 * The array values are the labels, while the array keys are the corresponding checkbox values.
Qiang Xue committed
783 784
	 * @param array $options options (name => config) for the checkbox list container tag.
	 * The following options are specially handled:
Qiang Xue committed
785
	 *
Qiang Xue committed
786
	 * - tag: string, the tag name of the container element.
Qiang Xue committed
787 788
	 * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
	 *   By setting this option, a hidden input will be generated.
789 790
	 * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
	 *   This option is ignored if `item` option is set.
Qiang Xue committed
791
	 * - separator: string, the HTML code that separates items.
792
	 * - itemOptions: array, the options for generating the radio button tag using [[checkbox()]].
Qiang Xue committed
793 794 795
	 * - item: callable, a callback that can be used to customize the generation of the HTML code
	 *   corresponding to a single item in $items. The signature of this callback must be:
	 *
796 797 798
	 *   ~~~
	 *   function ($index, $label, $name, $checked, $value)
	 *   ~~~
Qiang Xue committed
799
	 *
800 801 802
	 *   where $index is the zero-based index of the checkbox in the whole list; $label
	 *   is the label for the checkbox; and $name, $value and $checked represent the name,
	 *   value and the checked status of the checkbox input, respectively.
803
	 *
804
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
805
	 *
Qiang Xue committed
806 807
	 * @return string the generated checkbox list
	 */
Alexander Makarov committed
808
	public static function checkboxList($name, $selection = null, $items = [], $options = [])
Qiang Xue committed
809 810 811 812 813 814
	{
		if (substr($name, -2) !== '[]') {
			$name .= '[]';
		}

		$formatter = isset($options['item']) ? $options['item'] : null;
815
		$itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
816
		$encode = !isset($options['encode']) || $options['encode'];
Alexander Makarov committed
817
		$lines = [];
Qiang Xue committed
818 819 820 821 822 823 824 825
		$index = 0;
		foreach ($items as $value => $label) {
			$checked = $selection !== null &&
				(!is_array($selection) && !strcmp($value, $selection)
					|| is_array($selection) && in_array($value, $selection));
			if ($formatter !== null) {
				$lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
			} else {
826
				$lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [
Qiang Xue committed
827 828
					'value' => $value,
					'label' => $encode ? static::encode($label) : $label,
829
				]));
Qiang Xue committed
830 831 832 833 834 835 836 837 838 839 840 841 842
			}
			$index++;
		}

		if (isset($options['unselect'])) {
			// add a hidden field so that if the list box has no option being selected, it still submits a value
			$name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
			$hidden = static::hiddenInput($name2, $options['unselect']);
		} else {
			$hidden = '';
		}
		$separator = isset($options['separator']) ? $options['separator'] : "\n";

Qiang Xue committed
843
		$tag = isset($options['tag']) ? $options['tag'] : 'div';
844
		unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']);
Qiang Xue committed
845 846

		return $hidden . static::tag($tag, implode($separator, $lines), $options);
Qiang Xue committed
847 848 849 850 851 852 853 854
	}

	/**
	 * Generates a list of radio buttons.
	 * A radio button list is like a checkbox list, except that it only allows single selection.
	 * @param string $name the name attribute of each radio button.
	 * @param string|array $selection the selected value(s).
	 * @param array $items the data item used to generate the radio buttons.
Qiang Xue committed
855
	 * The array values are the labels, while the array keys are the corresponding radio button values.
Qiang Xue committed
856
	 * @param array $options options (name => config) for the radio button list. The following options are supported:
Qiang Xue committed
857 858 859
	 *
	 * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
	 *   By setting this option, a hidden input will be generated.
860 861
	 * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
	 *   This option is ignored if `item` option is set.
Qiang Xue committed
862
	 * - separator: string, the HTML code that separates items.
863
	 * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
Qiang Xue committed
864 865 866
	 * - item: callable, a callback that can be used to customize the generation of the HTML code
	 *   corresponding to a single item in $items. The signature of this callback must be:
	 *
867 868 869
	 *   ~~~
	 *   function ($index, $label, $name, $checked, $value)
	 *   ~~~
Qiang Xue committed
870
	 *
871 872 873
	 *   where $index is the zero-based index of the radio button in the whole list; $label
	 *   is the label for the radio button; and $name, $value and $checked represent the name,
	 *   value and the checked status of the radio button input, respectively.
874
	 *
875
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
876
	 *
Qiang Xue committed
877 878
	 * @return string the generated radio button list
	 */
Alexander Makarov committed
879
	public static function radioList($name, $selection = null, $items = [], $options = [])
Qiang Xue committed
880
	{
881
		$encode = !isset($options['encode']) || $options['encode'];
Qiang Xue committed
882
		$formatter = isset($options['item']) ? $options['item'] : null;
883
		$itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
Alexander Makarov committed
884
		$lines = [];
Qiang Xue committed
885 886 887 888 889 890 891 892
		$index = 0;
		foreach ($items as $value => $label) {
			$checked = $selection !== null &&
				(!is_array($selection) && !strcmp($value, $selection)
					|| is_array($selection) && in_array($value, $selection));
			if ($formatter !== null) {
				$lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
			} else {
893
				$lines[] = static::radio($name, $checked, array_merge($itemOptions, [
Qiang Xue committed
894 895
					'value' => $value,
					'label' => $encode ? static::encode($label) : $label,
896
				]));
Qiang Xue committed
897 898 899 900 901 902 903 904 905 906 907 908
			}
			$index++;
		}

		$separator = isset($options['separator']) ? $options['separator'] : "\n";
		if (isset($options['unselect'])) {
			// add a hidden field so that if the list box has no option being selected, it still submits a value
			$hidden = static::hiddenInput($name, $options['unselect']);
		} else {
			$hidden = '';
		}

Qiang Xue committed
909
		$tag = isset($options['tag']) ? $options['tag'] : 'div';
910
		unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']);
Qiang Xue committed
911 912

		return $hidden . static::tag($tag, implode($separator, $lines), $options);
Qiang Xue committed
913 914
	}

915 916 917 918 919 920 921
	/**
	 * Generates an unordered list.
	 * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
	 * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
	 * @param array $options options (name => config) for the radio button list. The following options are supported:
	 *
	 * - encode: boolean, whether to HTML-encode the items. Defaults to true.
922 923
	 *   This option is ignored if the `item` option is specified.
	 * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
924 925 926
	 * - item: callable, a callback that is used to generate each individual list item.
	 *   The signature of this callback must be:
	 *
927 928 929
	 *   ~~~
	 *   function ($item, $index)
	 *   ~~~
930
	 *
931 932
	 *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
	 *   the whole list item tag.
933
	 *
934
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
935
	 *
936 937
	 * @return string the generated unordered list. An empty string is returned if `$items` is empty.
	 */
Alexander Makarov committed
938
	public static function ul($items, $options = [])
939 940 941 942 943 944 945
	{
		if (empty($items)) {
			return '';
		}
		$tag = isset($options['tag']) ? $options['tag'] : 'ul';
		$encode = !isset($options['encode']) || $options['encode'];
		$formatter = isset($options['item']) ? $options['item'] : null;
Alexander Makarov committed
946
		$itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
947
		unset($options['tag'], $options['encode'], $options['item'], $options['itemOptions']);
Alexander Makarov committed
948
		$results = [];
949 950
		foreach ($items as $index => $item) {
			if ($formatter !== null) {
Qiang Xue committed
951
				$results[] = call_user_func($formatter, $item, $index);
952
			} else {
953
				$results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
954 955 956 957 958 959 960 961 962 963 964 965
			}
		}
		return static::tag($tag, "\n" . implode("\n", $results) . "\n", $options);
	}

	/**
	 * Generates an ordered list.
	 * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
	 * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
	 * @param array $options options (name => config) for the radio button list. The following options are supported:
	 *
	 * - encode: boolean, whether to HTML-encode the items. Defaults to true.
966 967
	 *   This option is ignored if the `item` option is specified.
	 * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
968 969 970
	 * - item: callable, a callback that is used to generate each individual list item.
	 *   The signature of this callback must be:
	 *
971 972 973
	 *   ~~~
	 *   function ($item, $index)
	 *   ~~~
974
	 *
975 976
	 *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
	 *   the whole list item tag.
977
	 *
978
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
979
	 *
980 981
	 * @return string the generated ordered list. An empty string is returned if `$items` is empty.
	 */
Alexander Makarov committed
982
	public static function ol($items, $options = [])
983 984 985 986 987
	{
		$options['tag'] = 'ol';
		return static::ul($items, $options);
	}

Qiang Xue committed
988 989 990 991 992 993 994 995 996 997 998
	/**
	 * Generates a label tag for the given model attribute.
	 * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
	 * If a value is null, the corresponding attribute will not be rendered.
	 * The following options are specially handled:
	 *
999
	 * - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
Qiang Xue committed
1000 1001
	 *   If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
	 *   (after encoding).
Qiang Xue committed
1002
	 *
1003
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1004
	 *
Qiang Xue committed
1005 1006
	 * @return string the generated label tag
	 */
Alexander Makarov committed
1007
	public static function activeLabel($model, $attribute, $options = [])
Qiang Xue committed
1008
	{
1009
		$for = array_key_exists('for', $options) ? $options['for'] : static::getInputId($model, $attribute);
Qiang Xue committed
1010 1011
		$attribute = static::getAttributeName($attribute);
		$label = isset($options['label']) ? $options['label'] : static::encode($model->getAttributeLabel($attribute));
Qiang Xue committed
1012
		unset($options['label'], $options['for']);
Qiang Xue committed
1013 1014 1015
		return static::label($label, $for, $options);
	}

Qiang Xue committed
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
	/**
	 * Generates a tag that contains the first validation error of the specified model attribute.
	 * Note that even if there is no validation error, this method will still return an empty error tag.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
	 * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
	 *
	 * The following options are specially handled:
	 *
Qiang Xue committed
1027
	 * - tag: this specifies the tag name. If not set, "div" will be used.
Qiang Xue committed
1028
	 *
1029
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1030
	 *
Qiang Xue committed
1031 1032
	 * @return string the generated label tag
	 */
Alexander Makarov committed
1033
	public static function error($model, $attribute, $options = [])
Qiang Xue committed
1034 1035 1036
	{
		$attribute = static::getAttributeName($attribute);
		$error = $model->getFirstError($attribute);
Qiang Xue committed
1037
		$tag = isset($options['tag']) ? $options['tag'] : 'div';
Qiang Xue committed
1038 1039 1040 1041
		unset($options['tag']);
		return Html::tag($tag, Html::encode($error), $options);
	}

Qiang Xue committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
	/**
	 * Generates an input tag for the given model attribute.
	 * This method will generate the "name" and "value" tag attributes automatically for the model attribute
	 * unless they are explicitly specified in `$options`.
	 * @param string $type the input type (e.g. 'text', 'password')
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1052
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
1053 1054
	 * @return string the generated input tag
	 */
Alexander Makarov committed
1055
	public static function activeInput($type, $model, $attribute, $options = [])
Qiang Xue committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
	{
		$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
		$value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
		if (!array_key_exists('id', $options)) {
			$options['id'] = static::getInputId($model, $attribute);
		}
		return static::input($type, $name, $value, $options);
	}

	/**
	 * Generates a text input tag for the given model attribute.
	 * This method will generate the "name" and "value" tag attributes automatically for the model attribute
	 * unless they are explicitly specified in `$options`.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1074
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
1075 1076
	 * @return string the generated input tag
	 */
Alexander Makarov committed
1077
	public static function activeTextInput($model, $attribute, $options = [])
Qiang Xue committed
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
	{
		return static::activeInput('text', $model, $attribute, $options);
	}

	/**
	 * Generates a hidden input tag for the given model attribute.
	 * This method will generate the "name" and "value" tag attributes automatically for the model attribute
	 * unless they are explicitly specified in `$options`.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1091
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
1092 1093
	 * @return string the generated input tag
	 */
Alexander Makarov committed
1094
	public static function activeHiddenInput($model, $attribute, $options = [])
Qiang Xue committed
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
	{
		return static::activeInput('hidden', $model, $attribute, $options);
	}

	/**
	 * Generates a password input tag for the given model attribute.
	 * This method will generate the "name" and "value" tag attributes automatically for the model attribute
	 * unless they are explicitly specified in `$options`.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1108
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
1109 1110
	 * @return string the generated input tag
	 */
Alexander Makarov committed
1111
	public static function activePasswordInput($model, $attribute, $options = [])
Qiang Xue committed
1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
	{
		return static::activeInput('password', $model, $attribute, $options);
	}

	/**
	 * Generates a file input tag for the given model attribute.
	 * This method will generate the "name" and "value" tag attributes automatically for the model attribute
	 * unless they are explicitly specified in `$options`.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1125
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
1126 1127
	 * @return string the generated input tag
	 */
Alexander Makarov committed
1128
	public static function activeFileInput($model, $attribute, $options = [])
Qiang Xue committed
1129
	{
1130 1131
		// add a hidden field so that if a model only has a file field, we can
		// still use isset($_POST[$modelClass]) to detect if the input is submitted
Alexander Makarov committed
1132
		return static::activeHiddenInput($model, $attribute, ['id' => null, 'value' => ''])
1133
			. static::activeInput('file', $model, $attribute, $options);
Qiang Xue committed
1134 1135 1136 1137 1138 1139 1140 1141 1142 1143
	}

	/**
	 * Generates a textarea tag for the given model attribute.
	 * The model attribute value will be used as the content in the textarea.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. These will be rendered as
	 * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1144
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
1145 1146
	 * @return string the generated textarea tag
	 */
Alexander Makarov committed
1147
	public static function activeTextarea($model, $attribute, $options = [])
Qiang Xue committed
1148
	{
1149
		$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
Qiang Xue committed
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168
		$value = static::getAttributeValue($model, $attribute);
		if (!array_key_exists('id', $options)) {
			$options['id'] = static::getInputId($model, $attribute);
		}
		return static::textarea($name, $value, $options);
	}

	/**
	 * Generates a radio button tag for the given model attribute.
	 * This method will generate the "checked" tag attribute according to the model attribute value.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
	 *
	 * - uncheck: string, the value associated with the uncheck state of the radio button. If not set,
	 *   it will take the default value '0'. This method will render a hidden input so that if the radio button
	 *   is not checked and is submitted, the value of this attribute will still be submitted to the server
	 *   via the hidden input.
1169 1170 1171 1172
	 * - label: string, a label displayed next to the radio button.  It will NOT be HTML-encoded. Therefore you can pass
	 *   in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
	 *   When this option is specified, the radio button will be enclosed by a label tag.
	 * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
Qiang Xue committed
1173 1174 1175 1176
	 *
	 * The rest of the options will be rendered as the attributes of the resulting tag. The values will
	 * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
	 *
1177
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1178
	 *
Qiang Xue committed
1179 1180
	 * @return string the generated radio button tag
	 */
Alexander Makarov committed
1181
	public static function activeRadio($model, $attribute, $options = [])
Qiang Xue committed
1182 1183
	{
		$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1184 1185 1186 1187 1188
		$value = static::getAttributeValue($model, $attribute);

		if (!array_key_exists('value', $options)) {
			$options['value'] = '1';
		}
Qiang Xue committed
1189
		if (!array_key_exists('uncheck', $options)) {
1190
			$options['uncheck'] = '0';
Qiang Xue committed
1191
		}
1192

Qiang Xue committed
1193
		$checked = "$value" === "{$options['value']}";
1194

Qiang Xue committed
1195 1196 1197
		if (!array_key_exists('id', $options)) {
			$options['id'] = static::getInputId($model, $attribute);
		}
1198
		return static::radio($name, $checked, $options);
Qiang Xue committed
1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212
	}

	/**
	 * Generates a checkbox tag for the given model attribute.
	 * This method will generate the "checked" tag attribute according to the model attribute value.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
	 *
	 * - uncheck: string, the value associated with the uncheck state of the radio button. If not set,
	 *   it will take the default value '0'. This method will render a hidden input so that if the radio button
	 *   is not checked and is submitted, the value of this attribute will still be submitted to the server
	 *   via the hidden input.
1213 1214 1215 1216
	 * - label: string, a label displayed next to the checkbox.  It will NOT be HTML-encoded. Therefore you can pass
	 *   in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
	 *   When this option is specified, the checkbox will be enclosed by a label tag.
	 * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
Qiang Xue committed
1217 1218 1219
	 *
	 * The rest of the options will be rendered as the attributes of the resulting tag. The values will
	 * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1220
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
1221 1222 1223
	 *
	 * @return string the generated checkbox tag
	 */
Alexander Makarov committed
1224
	public static function activeCheckbox($model, $attribute, $options = [])
Qiang Xue committed
1225 1226
	{
		$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1227 1228
		$value = static::getAttributeValue($model, $attribute);

1229 1230 1231
		if (!array_key_exists('value', $options)) {
			$options['value'] = '1';
		}
Qiang Xue committed
1232
		if (!array_key_exists('uncheck', $options)) {
1233
			$options['uncheck'] = '0';
Qiang Xue committed
1234
		}
1235

Qiang Xue committed
1236
		$checked = "$value" === "{$options['value']}";
1237

Qiang Xue committed
1238 1239 1240
		if (!array_key_exists('id', $options)) {
			$options['id'] = static::getInputId($model, $attribute);
		}
1241
		return static::checkbox($name, $checked, $options);
Qiang Xue committed
1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
	}

	/**
	 * Generates a drop-down list for the given model attribute.
	 * The selection of the drop-down list is taken from the value of the model attribute.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $items the option data items. The array keys are option values, and the array values
	 * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
	 * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
	 * If you have a list of data models, you may convert them into the format described above using
	 * [[\yii\helpers\ArrayHelper::map()]].
	 *
	 * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
	 * the labels will also be HTML-encoded.
	 * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
	 *
	 * - prompt: string, a prompt text to be displayed as the first option;
	 * - options: array, the attributes for the select option tags. The array keys must be valid option values,
	 *   and the array values are the extra attributes for the corresponding option tags. For example,
	 *
1264 1265 1266 1267 1268 1269
	 *   ~~~
	 *   [
	 *       'value1' => ['disabled' => true],
	 *       'value2' => ['label' => 'value 2'],
	 *   ];
	 *   ~~~
Qiang Xue committed
1270 1271 1272 1273 1274 1275
	 *
	 * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
	 *   except that the array keys represent the optgroup labels specified in $items.
	 *
	 * The rest of the options will be rendered as the attributes of the resulting tag. The values will
	 * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1276
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
1277 1278 1279
	 *
	 * @return string the generated drop-down list tag
	 */
Alexander Makarov committed
1280
	public static function activeDropDownList($model, $attribute, $items, $options = [])
Qiang Xue committed
1281
	{
1282 1283 1284
		if (!empty($options['multiple'])) {
			return static::activeListBox($model, $attribute, $items, $options);
		}
Qiang Xue committed
1285
		$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1286
		$selection = static::getAttributeValue($model, $attribute);
Qiang Xue committed
1287 1288 1289
		if (!array_key_exists('id', $options)) {
			$options['id'] = static::getInputId($model, $attribute);
		}
1290
		return static::dropDownList($name, $selection, $items, $options);
Qiang Xue committed
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312
	}

	/**
	 * Generates a list box.
	 * The selection of the list box is taken from the value of the model attribute.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $items the option data items. The array keys are option values, and the array values
	 * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
	 * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
	 * If you have a list of data models, you may convert them into the format described above using
	 * [[\yii\helpers\ArrayHelper::map()]].
	 *
	 * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
	 * the labels will also be HTML-encoded.
	 * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
	 *
	 * - prompt: string, a prompt text to be displayed as the first option;
	 * - options: array, the attributes for the select option tags. The array keys must be valid option values,
	 *   and the array values are the extra attributes for the corresponding option tags. For example,
	 *
1313 1314 1315 1316 1317 1318
	 *   ~~~
	 *   [
	 *       'value1' => ['disabled' => true],
	 *       'value2' => ['label' => 'value 2'],
	 *   ];
	 *   ~~~
Qiang Xue committed
1319 1320 1321 1322 1323 1324 1325 1326 1327
	 *
	 * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
	 *   except that the array keys represent the optgroup labels specified in $items.
	 * - unselect: string, the value that will be submitted when no option is selected.
	 *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
	 *   mode, we can still obtain the posted unselect value.
	 *
	 * The rest of the options will be rendered as the attributes of the resulting tag. The values will
	 * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1328
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
Qiang Xue committed
1329 1330 1331
	 *
	 * @return string the generated list box tag
	 */
Alexander Makarov committed
1332
	public static function activeListBox($model, $attribute, $items, $options = [])
Qiang Xue committed
1333 1334
	{
		$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1335
		$selection = static::getAttributeValue($model, $attribute);
Qiang Xue committed
1336
		if (!array_key_exists('unselect', $options)) {
1337
			$options['unselect'] = '';
Qiang Xue committed
1338 1339 1340 1341
		}
		if (!array_key_exists('id', $options)) {
			$options['id'] = static::getInputId($model, $attribute);
		}
1342
		return static::listBox($name, $selection, $items, $options);
Qiang Xue committed
1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
	}

	/**
	 * Generates a list of checkboxes.
	 * A checkbox list allows multiple selection, like [[listBox()]].
	 * As a result, the corresponding submitted value is an array.
	 * The selection of the checkbox list is taken from the value of the model attribute.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $items the data item used to generate the checkboxes.
1354
	 * The array values are the labels, while the array keys are the corresponding checkbox values.
Qiang Xue committed
1355 1356 1357 1358
	 * Note that the labels will NOT be HTML-encoded, while the values will.
	 * @param array $options options (name => config) for the checkbox list. The following options are specially handled:
	 *
	 * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
1359 1360
	 *   You may set this option to be null to prevent default value submission.
	 *   If this option is not set, an empty string will be submitted.
Qiang Xue committed
1361 1362 1363 1364
	 * - separator: string, the HTML code that separates items.
	 * - item: callable, a callback that can be used to customize the generation of the HTML code
	 *   corresponding to a single item in $items. The signature of this callback must be:
	 *
1365 1366 1367
	 *   ~~~
	 *   function ($index, $label, $name, $checked, $value)
	 *   ~~~
Qiang Xue committed
1368
	 *
1369 1370 1371
	 *   where $index is the zero-based index of the checkbox in the whole list; $label
	 *   is the label for the checkbox; and $name, $value and $checked represent the name,
	 *   value and the checked status of the checkbox input.
1372
	 *
1373
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1374
	 *
Qiang Xue committed
1375 1376
	 * @return string the generated checkbox list
	 */
Alexander Makarov committed
1377
	public static function activeCheckboxList($model, $attribute, $items, $options = [])
Qiang Xue committed
1378 1379
	{
		$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1380
		$selection = static::getAttributeValue($model, $attribute);
Qiang Xue committed
1381
		if (!array_key_exists('unselect', $options)) {
1382
			$options['unselect'] = '';
Qiang Xue committed
1383
		}
Qiang Xue committed
1384 1385 1386
		if (!array_key_exists('id', $options)) {
			$options['id'] = static::getInputId($model, $attribute);
		}
1387
		return static::checkboxList($name, $selection, $items, $options);
Qiang Xue committed
1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
	}

	/**
	 * Generates a list of radio buttons.
	 * A radio button list is like a checkbox list, except that it only allows single selection.
	 * The selection of the radio buttons is taken from the value of the model attribute.
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
	 * about attribute expression.
	 * @param array $items the data item used to generate the radio buttons.
	 * The array keys are the labels, while the array values are the corresponding radio button values.
	 * Note that the labels will NOT be HTML-encoded, while the values will.
	 * @param array $options options (name => config) for the radio button list. The following options are specially handled:
	 *
	 * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
1403 1404
	 *   You may set this option to be null to prevent default value submission.
	 *   If this option is not set, an empty string will be submitted.
Qiang Xue committed
1405 1406 1407 1408
	 * - separator: string, the HTML code that separates items.
	 * - item: callable, a callback that can be used to customize the generation of the HTML code
	 *   corresponding to a single item in $items. The signature of this callback must be:
	 *
1409 1410 1411
	 *   ~~~
	 *   function ($index, $label, $name, $checked, $value)
	 *   ~~~
Qiang Xue committed
1412
	 *
1413 1414 1415
	 *   where $index is the zero-based index of the radio button in the whole list; $label
	 *   is the label for the radio button; and $name, $value and $checked represent the name,
	 *   value and the checked status of the radio button input.
1416
	 *
1417
	 * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1418
	 *
Qiang Xue committed
1419 1420
	 * @return string the generated radio button list
	 */
Alexander Makarov committed
1421
	public static function activeRadioList($model, $attribute, $items, $options = [])
Qiang Xue committed
1422 1423
	{
		$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1424
		$selection = static::getAttributeValue($model, $attribute);
Qiang Xue committed
1425
		if (!array_key_exists('unselect', $options)) {
1426
			$options['unselect'] = '';
Qiang Xue committed
1427
		}
Qiang Xue committed
1428 1429 1430
		if (!array_key_exists('id', $options)) {
			$options['id'] = static::getInputId($model, $attribute);
		}
1431
		return static::radioList($name, $selection, $items, $options);
Qiang Xue committed
1432 1433
	}

Qiang Xue committed
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
	/**
	 * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
	 * @param string|array $selection the selected value(s). This can be either a string for single selection
	 * or an array for multiple selections.
	 * @param array $items the option data items. The array keys are option values, and the array values
	 * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
	 * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
	 * If you have a list of data models, you may convert them into the format described above using
	 * [[\yii\helpers\ArrayHelper::map()]].
	 *
	 * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
	 * the labels will also be HTML-encoded.
	 * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
	 * This method will take out these elements, if any: "prompt", "options" and "groups". See more details
	 * in [[dropDownList()]] for the explanation of these elements.
	 *
	 * @return string the generated list options
	 */
Alexander Makarov committed
1452
	public static function renderSelectOptions($selection, $items, &$tagOptions = [])
Qiang Xue committed
1453
	{
Alexander Makarov committed
1454
		$lines = [];
Qiang Xue committed
1455 1456
		if (isset($tagOptions['prompt'])) {
			$prompt = str_replace(' ', '&nbsp;', static::encode($tagOptions['prompt']));
Alexander Makarov committed
1457
			$lines[] = static::tag('option', $prompt, ['value' => '']);
Qiang Xue committed
1458 1459
		}

Alexander Makarov committed
1460 1461
		$options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
		$groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
Qiang Xue committed
1462 1463 1464 1465
		unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);

		foreach ($items as $key => $value) {
			if (is_array($value)) {
Alexander Makarov committed
1466
				$groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
Qiang Xue committed
1467
				$groupAttrs['label'] = $key;
Alexander Makarov committed
1468
				$attrs = ['options' => $options, 'groups' => $groups];
Qiang Xue committed
1469 1470 1471
				$content = static::renderSelectOptions($selection, $value, $attrs);
				$lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
			} else {
Alexander Makarov committed
1472
				$attrs = isset($options[$key]) ? $options[$key] : [];
1473
				$attrs['value'] = (string)$key;
Qiang Xue committed
1474
				$attrs['selected'] = $selection !== null &&
Qiang Xue committed
1475
						(!is_array($selection) && !strcmp($key, $selection)
Qiang Xue committed
1476 1477 1478 1479 1480 1481 1482 1483 1484 1485
						|| is_array($selection) && in_array($key, $selection));
				$lines[] = static::tag('option', str_replace(' ', '&nbsp;', static::encode($value)), $attrs);
			}
		}

		return implode("\n", $lines);
	}

	/**
	 * Renders the HTML tag attributes.
1486
	 *
resurtm committed
1487 1488
	 * Attributes whose values are of boolean type will be treated as
	 * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
1489 1490 1491
	 *
	 * Attributes whose values are null will not be rendered.
	 *
1492 1493
	 * The values of attributes will be HTML-encoded using [[encode()]].
	 *
1494 1495 1496 1497 1498
	 * The "data" attribute is specially handled when it is receiving an array value. In this case,
	 * the array will be "expanded" and a list data attributes will be rendered. For example,
	 * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered:
	 * `data-id="1" data-name="yii"`.
	 *
Qiang Xue committed
1499 1500
	 * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
	 * @return string the rendering result. If the attributes are not empty, they will be rendered
1501
	 * into a string with a leading white space (so that it can be directly appended to the tag name
Qiang Xue committed
1502 1503 1504 1505 1506
	 * in a tag. If there is no attribute, an empty string will be returned.
	 */
	public static function renderTagAttributes($attributes)
	{
		if (count($attributes) > 1) {
Alexander Makarov committed
1507
			$sorted = [];
Qiang Xue committed
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
			foreach (static::$attributeOrder as $name) {
				if (isset($attributes[$name])) {
					$sorted[$name] = $attributes[$name];
				}
			}
			$attributes = array_merge($sorted, $attributes);
		}

		$html = '';
		foreach ($attributes as $name => $value) {
1518 1519
			if (is_bool($value)) {
				if ($value) {
1520
					$html .= " $name";
Qiang Xue committed
1521
				}
1522 1523
			} elseif (is_array($value) && $name === 'data') {
				foreach ($value as $n => $v) {
Qiang Xue committed
1524
					$html .= " $name-$n=\"" . static::encode($v) . '"';
1525
				}
Qiang Xue committed
1526 1527 1528 1529 1530 1531 1532
			} elseif ($value !== null) {
				$html .= " $name=\"" . static::encode($value) . '"';
			}
		}
		return $html;
	}

1533 1534 1535 1536 1537 1538 1539 1540 1541 1542
	/**
	 * Adds a CSS class to the specified options.
	 * If the CSS class is already in the options, it will not be added again.
	 * @param array $options the options to be modified.
	 * @param string $class the CSS class to be added
	 */
	public static function addCssClass(&$options, $class)
	{
		if (isset($options['class'])) {
			$classes = ' ' . $options['class'] . ' ';
1543
			if (strpos($classes, ' ' . $class . ' ') === false) {
1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570
				$options['class'] .= ' ' . $class;
			}
		} else {
			$options['class'] = $class;
		}
	}

	/**
	 * Removes a CSS class from the specified options.
	 * @param array $options the options to be modified.
	 * @param string $class the CSS class to be removed
	 */
	public static function removeCssClass(&$options, $class)
	{
		if (isset($options['class'])) {
			$classes = array_unique(preg_split('/\s+/', $options['class'] . ' ' . $class, -1, PREG_SPLIT_NO_EMPTY));
			if (($index = array_search($class, $classes)) !== false) {
				unset($classes[$index]);
			}
			if (empty($classes)) {
				unset($options['class']);
			} else {
				$options['class'] = implode(' ', $classes);
			}
		}
	}

1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686
	/**
	 * Adds the specified CSS style to the HTML options.
	 *
	 * If the options already contain a `style` element, the new style will be merged
	 * with the existing one. If a CSS property exists in both the new and the old styles,
	 * the old one may be overwritten if `$overwrite` is true.
	 *
	 * For example,
	 *
	 * ```php
	 * Html::addCssStyle($options, 'width: 100px; height: 200px');
	 * ```
	 *
	 * @param array $options the HTML options to be modified.
	 * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
	 * array (e.g. `['width' => '100px', 'height' => '200px']`).
	 * @param boolean $overwrite whether to overwrite existing CSS properties if the new style
	 * contain them too.
	 * @see removeCssStyle()
	 * @see cssStyleFromArray()
	 * @see cssStyleToArray()
	 */
	public static function addCssStyle(&$options, $style, $overwrite = true)
	{
		if (!empty($options['style'])) {
			$oldStyle = static::cssStyleToArray($options['style']);
			$newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
			if (!$overwrite) {
				foreach ($newStyle as $property => $value) {
					if (isset($oldStyle[$property])) {
						unset($newStyle[$property]);
					}
				}
			}
			$style = static::cssStyleFromArray(array_merge($oldStyle, $newStyle));
		}
		$options['style'] = $style;
	}

	/**
	 * Removes the specified CSS style from the HTML options.
	 *
	 * For example,
	 *
	 * ```php
	 * Html::removeCssStyle($options, ['width', 'height']);
	 * ```
	 *
	 * @param array $options the HTML options to be modified.
	 * @param string|array $properties the CSS properties to be removed. You may use a string
	 * if you are removing a single property.
	 * @see addCssStyle()
	 */
	public static function removeCssStyle(&$options, $properties)
	{
		if (!empty($options['style'])) {
			$style = static::cssStyleToArray($options['style']);
			foreach ((array)$properties as $property) {
				unset($style[$property]);
			}
			$options['style'] = static::cssStyleFromArray($style);
		}
	}

	/**
	 * Converts a CSS style array into a string representation.
	 *
	 * For example,
	 *
	 * ```php
	 * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
	 * // will display: 'width: 100px; height: 200px;'
	 * ```
	 *
	 * @param array $style the CSS style array. The array keys are the CSS property names,
	 * and the array values are the corresponding CSS property values.
	 * @return string the CSS style string. If the CSS style is empty, a null will be returned.
	 */
	public static function cssStyleFromArray(array $style)
	{
		$result = '';
		foreach ($style as $name => $value) {
			$result .= "$name: $value; ";
		}
		// return null if empty to avoid rendering the "style" attribute
		return $result === '' ? null : rtrim($result);
	}

	/**
	 * Converts a CSS style string into an array representation.
	 *
	 * The array keys are the CSS property names, and the array values
	 * are the corresponding CSS property values.
	 *
	 * For example,
	 *
	 * ```php
	 * print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
	 * // will display: ['width' => '100px', 'height' => '200px']
	 * ```
	 *
	 * @param string $style the CSS style string
	 * @return array the array representation of the CSS style
	 */
	public static function cssStyleToArray($style)
	{
		$result = [];
		foreach (explode(';', $style) as $property) {
			$property = explode(':', $property);
			if (count($property) > 1) {
				$result[trim($property[0])] = trim($property[1]);
			}
		}
		return $result;
	}

Qiang Xue committed
1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
	/**
	 * Returns the real attribute name from the given attribute expression.
	 *
	 * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
	 * It is mainly used in tabular data input and/or input of array type. Below are some examples:
	 *
	 * - `[0]content` is used in tabular data input to represent the "content" attribute
	 *   for the first model in tabular input;
	 * - `dates[0]` represents the first array element of the "dates" attribute;
	 * - `[0]dates[0]` represents the first array element of the "dates" attribute
	 *   for the first model in tabular input.
	 *
	 * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
	 * @param string $attribute the attribute name or expression
	 * @return string the attribute name without prefix and suffix.
	 * @throws InvalidParamException if the attribute name contains non-word characters.
	 */
	public static function getAttributeName($attribute)
	{
		if (preg_match('/(^|.*\])(\w+)(\[.*|$)/', $attribute, $matches)) {
			return $matches[2];
		} else {
			throw new InvalidParamException('Attribute name must contain word characters only.');
		}
	}

	/**
	 * Returns the value of the specified attribute name or expression.
	 *
	 * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
	 * See [[getAttributeName()]] for more details about attribute expression.
	 *
1719 1720 1721
	 * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
	 * the primary value(s) of the AR instance(s) will be returned instead.
	 *
Qiang Xue committed
1722 1723
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression
1724
	 * @return string|array the corresponding attribute value
Qiang Xue committed
1725 1726 1727 1728 1729 1730 1731 1732
	 * @throws InvalidParamException if the attribute name contains non-word characters.
	 */
	public static function getAttributeValue($model, $attribute)
	{
		if (!preg_match('/(^|.*\])(\w+)(\[.*|$)/', $attribute, $matches)) {
			throw new InvalidParamException('Attribute name must contain word characters only.');
		}
		$attribute = $matches[2];
1733 1734 1735
		$value = $model->$attribute;
		if ($matches[3] !== '') {
			foreach (explode('][', trim($matches[3], '[]')) as $id) {
Qiang Xue committed
1736 1737 1738 1739 1740 1741 1742
				if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
					$value = $value[$id];
				} else {
					return null;
				}
			}
		}
1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756

		// https://github.com/yiisoft/yii2/issues/1457
		if (is_array($value)) {
			foreach ($value as $i => $v) {
				if ($v instanceof ActiveRecordInterface) {
					$v = $v->getPrimaryKey(false);
					$value[$i] = is_array($v) ? json_encode($v) : $v;
				}
			}
		} elseif ($value instanceof ActiveRecordInterface) {
			$value = $value->getPrimaryKey(false);
			return is_array($value) ? json_encode($value) : $value;
		}
		return $value;
Qiang Xue committed
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795
	}

	/**
	 * Generates an appropriate input name for the specified attribute name or expression.
	 *
	 * This method generates a name that can be used as the input name to collect user input
	 * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
	 * of the model and the given attribute name. For example, if the form name of the `Post` model
	 * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
	 *
	 * See [[getAttributeName()]] for explanation of attribute expression.
	 *
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression
	 * @return string the generated input name
	 * @throws InvalidParamException if the attribute name contains non-word characters.
	 */
	public static function getInputName($model, $attribute)
	{
		$formName = $model->formName();
		if (!preg_match('/(^|.*\])(\w+)(\[.*|$)/', $attribute, $matches)) {
			throw new InvalidParamException('Attribute name must contain word characters only.');
		}
		$prefix = $matches[1];
		$attribute = $matches[2];
		$suffix = $matches[3];
		if ($formName === '' && $prefix === '') {
			return $attribute . $suffix;
		} elseif ($formName !== '') {
			return $formName . $prefix . "[$attribute]" . $suffix;
		} else {
			throw new InvalidParamException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
		}
	}

	/**
	 * Generates an appropriate input ID for the specified attribute name or expression.
	 *
	 * This method converts the result [[getInputName()]] into a valid input ID.
Qiang Xue committed
1796
	 * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
Qiang Xue committed
1797 1798 1799 1800 1801 1802 1803
	 * @param Model $model the model object
	 * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
	 * @return string the generated input ID
	 * @throws InvalidParamException if the attribute name contains non-word characters.
	 */
	public static function getInputId($model, $attribute)
	{
1804
		$name = strtolower(static::getInputName($model, $attribute));
Alexander Makarov committed
1805
		return str_replace(['[]', '][', '[', ']', ' '], ['', '-', '-', '', '-'], $name);
Qiang Xue committed
1806
	}
Qiang Xue committed
1807
}