2134 linhas
99KB

  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\helpers;
  8. use Yii;
  9. use yii\base\InvalidParamException;
  10. use yii\db\ActiveRecordInterface;
  11. use yii\validators\StringValidator;
  12. use yii\web\Request;
  13. use yii\base\Model;
  14. /**
  15. * BaseHtml provides concrete implementation for [[Html]].
  16. *
  17. * Do not use BaseHtml. Use [[Html]] instead.
  18. *
  19. * @author Qiang Xue <qiang.xue@gmail.com>
  20. * @since 2.0
  21. */
  22. class BaseHtml
  23. {
  24. /**
  25. * @var array list of void elements (element name => 1)
  26. * @see http://www.w3.org/TR/html-markup/syntax.html#void-element
  27. */
  28. public static $voidElements = [
  29. 'area' => 1,
  30. 'base' => 1,
  31. 'br' => 1,
  32. 'col' => 1,
  33. 'command' => 1,
  34. 'embed' => 1,
  35. 'hr' => 1,
  36. 'img' => 1,
  37. 'input' => 1,
  38. 'keygen' => 1,
  39. 'link' => 1,
  40. 'meta' => 1,
  41. 'param' => 1,
  42. 'source' => 1,
  43. 'track' => 1,
  44. 'wbr' => 1,
  45. ];
  46. /**
  47. * @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes
  48. * that are rendered by [[renderTagAttributes()]].
  49. */
  50. public static $attributeOrder = [
  51. 'type',
  52. 'id',
  53. 'class',
  54. 'name',
  55. 'value',
  56. 'href',
  57. 'src',
  58. 'action',
  59. 'method',
  60. 'selected',
  61. 'checked',
  62. 'readonly',
  63. 'disabled',
  64. 'multiple',
  65. 'size',
  66. 'maxlength',
  67. 'width',
  68. 'height',
  69. 'rows',
  70. 'cols',
  71. 'alt',
  72. 'title',
  73. 'rel',
  74. 'media',
  75. ];
  76. /**
  77. * @var array list of tag attributes that should be specially handled when their values are of array type.
  78. * In particular, if the value of the `data` attribute is `['name' => 'xyz', 'age' => 13]`, two attributes
  79. * will be generated instead of one: `data-name="xyz" data-age="13"`.
  80. * @since 2.0.3
  81. */
  82. public static $dataAttributes = ['data', 'data-ng', 'ng'];
  83. /**
  84. * Encodes special characters into HTML entities.
  85. * The [[\yii\base\Application::charset|application charset]] will be used for encoding.
  86. * @param string $content the content to be encoded
  87. * @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false,
  88. * HTML entities in `$content` will not be further encoded.
  89. * @return string the encoded content
  90. * @see decode()
  91. * @see http://www.php.net/manual/en/function.htmlspecialchars.php
  92. */
  93. public static function encode($content, $doubleEncode = true)
  94. {
  95. return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode);
  96. }
  97. /**
  98. * Decodes special HTML entities back to the corresponding characters.
  99. * This is the opposite of [[encode()]].
  100. * @param string $content the content to be decoded
  101. * @return string the decoded content
  102. * @see encode()
  103. * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
  104. */
  105. public static function decode($content)
  106. {
  107. return htmlspecialchars_decode($content, ENT_QUOTES);
  108. }
  109. /**
  110. * Generates a complete HTML tag.
  111. * @param string|boolean|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
  112. * @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded.
  113. * If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks.
  114. * @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs.
  115. * These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  116. * If a value is null, the corresponding attribute will not be rendered.
  117. *
  118. * For example when using `['class' => 'my-class', 'target' => '_blank', 'value' => null]` it will result in the
  119. * html attributes rendered like this: `class="my-class" target="_blank"`.
  120. *
  121. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  122. *
  123. * @return string the generated HTML tag
  124. * @see beginTag()
  125. * @see endTag()
  126. */
  127. public static function tag($name, $content = '', $options = [])
  128. {
  129. if ($name === null || $name === false) {
  130. return $content;
  131. }
  132. $html = "<$name" . static::renderTagAttributes($options) . '>';
  133. return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>";
  134. }
  135. /**
  136. * Generates a start tag.
  137. * @param string|boolean|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
  138. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  139. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  140. * If a value is null, the corresponding attribute will not be rendered.
  141. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  142. * @return string the generated start tag
  143. * @see endTag()
  144. * @see tag()
  145. */
  146. public static function beginTag($name, $options = [])
  147. {
  148. if ($name === null || $name === false) {
  149. return '';
  150. }
  151. return "<$name" . static::renderTagAttributes($options) . '>';
  152. }
  153. /**
  154. * Generates an end tag.
  155. * @param string|boolean|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
  156. * @return string the generated end tag
  157. * @see beginTag()
  158. * @see tag()
  159. */
  160. public static function endTag($name)
  161. {
  162. if ($name === null || $name === false) {
  163. return '';
  164. }
  165. return "</$name>";
  166. }
  167. /**
  168. * Generates a style tag.
  169. * @param string $content the style content
  170. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  171. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  172. * If a value is null, the corresponding attribute will not be rendered.
  173. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  174. * @return string the generated style tag
  175. */
  176. public static function style($content, $options = [])
  177. {
  178. return static::tag('style', $content, $options);
  179. }
  180. /**
  181. * Generates a script tag.
  182. * @param string $content the script content
  183. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  184. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  185. * If a value is null, the corresponding attribute will not be rendered.
  186. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  187. * @return string the generated script tag
  188. */
  189. public static function script($content, $options = [])
  190. {
  191. return static::tag('script', $content, $options);
  192. }
  193. /**
  194. * Generates a link tag that refers to an external CSS file.
  195. * @param array|string $url the URL of the external CSS file. This parameter will be processed by [[Url::to()]].
  196. * @param array $options the tag options in terms of name-value pairs. The following option is specially handled:
  197. *
  198. * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
  199. * the generated `link` tag will be enclosed within the conditional comments. This is mainly useful
  200. * for supporting old versions of IE browsers.
  201. * - noscript: if set to true, `link` tag will be wrapped into `<noscript>` tags.
  202. *
  203. * The rest of the options will be rendered as the attributes of the resulting link tag. The values will
  204. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  205. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  206. * @return string the generated link tag
  207. * @see Url::to()
  208. */
  209. public static function cssFile($url, $options = [])
  210. {
  211. if (!isset($options['rel'])) {
  212. $options['rel'] = 'stylesheet';
  213. }
  214. $options['href'] = Url::to($url);
  215. if (isset($options['condition'])) {
  216. $condition = $options['condition'];
  217. unset($options['condition']);
  218. return self::wrapIntoCondition(static::tag('link', '', $options), $condition);
  219. } elseif (isset($options['noscript']) && $options['noscript'] === true) {
  220. unset($options['noscript']);
  221. return '<noscript>' . static::tag('link', '', $options) . '</noscript>';
  222. } else {
  223. return static::tag('link', '', $options);
  224. }
  225. }
  226. /**
  227. * Generates a script tag that refers to an external JavaScript file.
  228. * @param string $url the URL of the external JavaScript file. This parameter will be processed by [[Url::to()]].
  229. * @param array $options the tag options in terms of name-value pairs. The following option is specially handled:
  230. *
  231. * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
  232. * the generated `script` tag will be enclosed within the conditional comments. This is mainly useful
  233. * for supporting old versions of IE browsers.
  234. *
  235. * The rest of the options will be rendered as the attributes of the resulting script tag. The values will
  236. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  237. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  238. * @return string the generated script tag
  239. * @see Url::to()
  240. */
  241. public static function jsFile($url, $options = [])
  242. {
  243. $options['src'] = Url::to($url);
  244. if (isset($options['condition'])) {
  245. $condition = $options['condition'];
  246. unset($options['condition']);
  247. return self::wrapIntoCondition(static::tag('script', '', $options), $condition);
  248. } else {
  249. return static::tag('script', '', $options);
  250. }
  251. }
  252. /**
  253. * Wraps given content into conditional comments for IE, e.g., `lt IE 9`.
  254. * @param string $content raw HTML content.
  255. * @param string $condition condition string.
  256. * @return string generated HTML.
  257. */
  258. private static function wrapIntoCondition($content, $condition)
  259. {
  260. if (strpos($condition, '!IE') !== false) {
  261. return "<!--[if $condition]><!-->\n" . $content . "\n<!--<![endif]-->";
  262. }
  263. return "<!--[if $condition]>\n" . $content . "\n<![endif]-->";
  264. }
  265. /**
  266. * Generates the meta tags containing CSRF token information.
  267. * @return string the generated meta tags
  268. * @see Request::enableCsrfValidation
  269. */
  270. public static function csrfMetaTags()
  271. {
  272. $request = Yii::$app->getRequest();
  273. if ($request instanceof Request && $request->enableCsrfValidation) {
  274. return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n "
  275. . static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n";
  276. } else {
  277. return '';
  278. }
  279. }
  280. /**
  281. * Generates a form start tag.
  282. * @param array|string $action the form action URL. This parameter will be processed by [[Url::to()]].
  283. * @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive).
  284. * Since most browsers only support "post" and "get", if other methods are given, they will
  285. * be simulated using "post", and a hidden input will be added which contains the actual method type.
  286. * See [[\yii\web\Request::methodParam]] for more details.
  287. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  288. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  289. * If a value is null, the corresponding attribute will not be rendered.
  290. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  291. *
  292. * Special options:
  293. *
  294. * - `csrf`: whether to generate the CSRF hidden input. Defaults to true.
  295. *
  296. * @return string the generated form start tag.
  297. * @see endForm()
  298. */
  299. public static function beginForm($action = '', $method = 'post', $options = [])
  300. {
  301. $action = Url::to($action);
  302. $hiddenInputs = [];
  303. $request = Yii::$app->getRequest();
  304. if ($request instanceof Request) {
  305. if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) {
  306. // simulate PUT, DELETE, etc. via POST
  307. $hiddenInputs[] = static::hiddenInput($request->methodParam, $method);
  308. $method = 'post';
  309. }
  310. $csrf = ArrayHelper::remove($options, 'csrf', true);
  311. if ($csrf && $request->enableCsrfValidation && strcasecmp($method, 'post') === 0) {
  312. $hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken());
  313. }
  314. }
  315. if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) {
  316. // query parameters in the action are ignored for GET method
  317. // we use hidden fields to add them back
  318. foreach (explode('&', substr($action, $pos + 1)) as $pair) {
  319. if (($pos1 = strpos($pair, '=')) !== false) {
  320. $hiddenInputs[] = static::hiddenInput(
  321. urldecode(substr($pair, 0, $pos1)),
  322. urldecode(substr($pair, $pos1 + 1))
  323. );
  324. } else {
  325. $hiddenInputs[] = static::hiddenInput(urldecode($pair), '');
  326. }
  327. }
  328. $action = substr($action, 0, $pos);
  329. }
  330. $options['action'] = $action;
  331. $options['method'] = $method;
  332. $form = static::beginTag('form', $options);
  333. if (!empty($hiddenInputs)) {
  334. $form .= "\n" . implode("\n", $hiddenInputs);
  335. }
  336. return $form;
  337. }
  338. /**
  339. * Generates a form end tag.
  340. * @return string the generated tag
  341. * @see beginForm()
  342. */
  343. public static function endForm()
  344. {
  345. return '</form>';
  346. }
  347. /**
  348. * Generates a hyperlink tag.
  349. * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
  350. * such as an image tag. If this is coming from end users, you should consider [[encode()]]
  351. * it to prevent XSS attacks.
  352. * @param array|string|null $url the URL for the hyperlink tag. This parameter will be processed by [[Url::to()]]
  353. * and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute
  354. * will not be generated.
  355. *
  356. * If you want to use an absolute url you can call [[Url::to()]] yourself, before passing the URL to this method,
  357. * like this:
  358. *
  359. * ```php
  360. * Html::a('link text', Url::to($url, true))
  361. * ```
  362. *
  363. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  364. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  365. * If a value is null, the corresponding attribute will not be rendered.
  366. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  367. * @return string the generated hyperlink
  368. * @see \yii\helpers\Url::to()
  369. */
  370. public static function a($text, $url = null, $options = [])
  371. {
  372. if ($url !== null) {
  373. $options['href'] = Url::to($url);
  374. }
  375. return static::tag('a', $text, $options);
  376. }
  377. /**
  378. * Generates a mailto hyperlink.
  379. * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
  380. * such as an image tag. If this is coming from end users, you should consider [[encode()]]
  381. * it to prevent XSS attacks.
  382. * @param string $email email address. If this is null, the first parameter (link body) will be treated
  383. * as the email address and used.
  384. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  385. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  386. * If a value is null, the corresponding attribute will not be rendered.
  387. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  388. * @return string the generated mailto link
  389. */
  390. public static function mailto($text, $email = null, $options = [])
  391. {
  392. $options['href'] = 'mailto:' . ($email === null ? $text : $email);
  393. return static::tag('a', $text, $options);
  394. }
  395. /**
  396. * Generates an image tag.
  397. * @param array|string $src the image URL. This parameter will be processed by [[Url::to()]].
  398. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  399. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  400. * If a value is null, the corresponding attribute will not be rendered.
  401. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  402. * @return string the generated image tag
  403. */
  404. public static function img($src, $options = [])
  405. {
  406. $options['src'] = Url::to($src);
  407. if (!isset($options['alt'])) {
  408. $options['alt'] = '';
  409. }
  410. return static::tag('img', '', $options);
  411. }
  412. /**
  413. * Generates a label tag.
  414. * @param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code
  415. * such as an image tag. If this is is coming from end users, you should [[encode()]]
  416. * it to prevent XSS attacks.
  417. * @param string $for the ID of the HTML element that this label is associated with.
  418. * If this is null, the "for" attribute will not be generated.
  419. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  420. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  421. * If a value is null, the corresponding attribute will not be rendered.
  422. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  423. * @return string the generated label tag
  424. */
  425. public static function label($content, $for = null, $options = [])
  426. {
  427. $options['for'] = $for;
  428. return static::tag('label', $content, $options);
  429. }
  430. /**
  431. * Generates a button tag.
  432. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
  433. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
  434. * you should consider [[encode()]] it to prevent XSS attacks.
  435. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  436. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  437. * If a value is null, the corresponding attribute will not be rendered.
  438. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  439. * @return string the generated button tag
  440. */
  441. public static function button($content = 'Button', $options = [])
  442. {
  443. if (!isset($options['type'])) {
  444. $options['type'] = 'button';
  445. }
  446. return static::tag('button', $content, $options);
  447. }
  448. /**
  449. * Generates a submit button tag.
  450. *
  451. * Be careful when naming form elements such as submit buttons. According to the [jQuery documentation](https://api.jquery.com/submit/) there
  452. * are some reserved names that can cause conflicts, e.g. `submit`, `length`, or `method`.
  453. *
  454. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
  455. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
  456. * you should consider [[encode()]] it to prevent XSS attacks.
  457. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  458. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  459. * If a value is null, the corresponding attribute will not be rendered.
  460. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  461. * @return string the generated submit button tag
  462. */
  463. public static function submitButton($content = 'Submit', $options = [])
  464. {
  465. $options['type'] = 'submit';
  466. return static::button($content, $options);
  467. }
  468. /**
  469. * Generates a reset button tag.
  470. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
  471. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
  472. * you should consider [[encode()]] it to prevent XSS attacks.
  473. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  474. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  475. * If a value is null, the corresponding attribute will not be rendered.
  476. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  477. * @return string the generated reset button tag
  478. */
  479. public static function resetButton($content = 'Reset', $options = [])
  480. {
  481. $options['type'] = 'reset';
  482. return static::button($content, $options);
  483. }
  484. /**
  485. * Generates an input type of the given type.
  486. * @param string $type the type attribute.
  487. * @param string $name the name attribute. If it is null, the name attribute will not be generated.
  488. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  489. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  490. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  491. * If a value is null, the corresponding attribute will not be rendered.
  492. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  493. * @return string the generated input tag
  494. */
  495. public static function input($type, $name = null, $value = null, $options = [])
  496. {
  497. if (!isset($options['type'])) {
  498. $options['type'] = $type;
  499. }
  500. $options['name'] = $name;
  501. $options['value'] = $value === null ? null : (string) $value;
  502. return static::tag('input', '', $options);
  503. }
  504. /**
  505. * Generates an input button.
  506. * @param string $label the value attribute. If it is null, the value attribute will not be generated.
  507. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  508. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  509. * If a value is null, the corresponding attribute will not be rendered.
  510. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  511. * @return string the generated button tag
  512. */
  513. public static function buttonInput($label = 'Button', $options = [])
  514. {
  515. $options['type'] = 'button';
  516. $options['value'] = $label;
  517. return static::tag('input', '', $options);
  518. }
  519. /**
  520. * Generates a submit input button.
  521. *
  522. * Be careful when naming form elements such as submit buttons. According to the [jQuery documentation](https://api.jquery.com/submit/) there
  523. * are some reserved names that can cause conflicts, e.g. `submit`, `length`, or `method`.
  524. *
  525. * @param string $label the value attribute. If it is null, the value attribute will not be generated.
  526. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  527. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  528. * If a value is null, the corresponding attribute will not be rendered.
  529. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  530. * @return string the generated button tag
  531. */
  532. public static function submitInput($label = 'Submit', $options = [])
  533. {
  534. $options['type'] = 'submit';
  535. $options['value'] = $label;
  536. return static::tag('input', '', $options);
  537. }
  538. /**
  539. * Generates a reset input button.
  540. * @param string $label the value attribute. If it is null, the value attribute will not be generated.
  541. * @param array $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]].
  542. * Attributes whose value is null will be ignored and not put in the tag returned.
  543. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  544. * @return string the generated button tag
  545. */
  546. public static function resetInput($label = 'Reset', $options = [])
  547. {
  548. $options['type'] = 'reset';
  549. $options['value'] = $label;
  550. return static::tag('input', '', $options);
  551. }
  552. /**
  553. * Generates a text input field.
  554. * @param string $name the name attribute.
  555. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  556. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  557. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  558. * If a value is null, the corresponding attribute will not be rendered.
  559. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  560. * @return string the generated text input tag
  561. */
  562. public static function textInput($name, $value = null, $options = [])
  563. {
  564. return static::input('text', $name, $value, $options);
  565. }
  566. /**
  567. * Generates a hidden input field.
  568. * @param string $name the name attribute.
  569. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  570. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  571. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  572. * If a value is null, the corresponding attribute will not be rendered.
  573. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  574. * @return string the generated hidden input tag
  575. */
  576. public static function hiddenInput($name, $value = null, $options = [])
  577. {
  578. return static::input('hidden', $name, $value, $options);
  579. }
  580. /**
  581. * Generates a password input field.
  582. * @param string $name the name attribute.
  583. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  584. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  585. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  586. * If a value is null, the corresponding attribute will not be rendered.
  587. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  588. * @return string the generated password input tag
  589. */
  590. public static function passwordInput($name, $value = null, $options = [])
  591. {
  592. return static::input('password', $name, $value, $options);
  593. }
  594. /**
  595. * Generates a file input field.
  596. * To use a file input field, you should set the enclosing form's "enctype" attribute to
  597. * be "multipart/form-data". After the form is submitted, the uploaded file information
  598. * can be obtained via $_FILES[$name] (see PHP documentation).
  599. * @param string $name the name attribute.
  600. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  601. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  602. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  603. * If a value is null, the corresponding attribute will not be rendered.
  604. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  605. * @return string the generated file input tag
  606. */
  607. public static function fileInput($name, $value = null, $options = [])
  608. {
  609. return static::input('file', $name, $value, $options);
  610. }
  611. /**
  612. * Generates a text area input.
  613. * @param string $name the input name
  614. * @param string $value the input value. Note that it will be encoded using [[encode()]].
  615. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  616. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  617. * If a value is null, the corresponding attribute will not be rendered.
  618. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  619. * @return string the generated text area tag
  620. */
  621. public static function textarea($name, $value = '', $options = [])
  622. {
  623. $options['name'] = $name;
  624. return static::tag('textarea', static::encode($value), $options);
  625. }
  626. /**
  627. * Generates a radio button input.
  628. * @param string $name the name attribute.
  629. * @param boolean $checked whether the radio button should be checked.
  630. * @param array $options the tag options in terms of name-value pairs.
  631. * See [[booleanInput()]] for details about accepted attributes.
  632. *
  633. * @return string the generated radio button tag
  634. */
  635. public static function radio($name, $checked = false, $options = [])
  636. {
  637. return static::booleanInput('radio', $name, $checked, $options);
  638. }
  639. /**
  640. * Generates a checkbox input.
  641. * @param string $name the name attribute.
  642. * @param boolean $checked whether the checkbox should be checked.
  643. * @param array $options the tag options in terms of name-value pairs.
  644. * See [[booleanInput()]] for details about accepted attributes.
  645. *
  646. * @return string the generated checkbox tag
  647. */
  648. public static function checkbox($name, $checked = false, $options = [])
  649. {
  650. return static::booleanInput('checkbox', $name, $checked, $options);
  651. }
  652. /**
  653. * Generates a boolean input.
  654. * @param string $type the input type. This can be either `radio` or `checkbox`.
  655. * @param string $name the name attribute.
  656. * @param boolean $checked whether the checkbox should be checked.
  657. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  658. *
  659. * - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute
  660. * is present, a hidden input will be generated so that if the checkbox is not checked and is submitted,
  661. * the value of this attribute will still be submitted to the server via the hidden input.
  662. * - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
  663. * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
  664. * When this option is specified, the checkbox will be enclosed by a label tag.
  665. * - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option.
  666. *
  667. * The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will
  668. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  669. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  670. *
  671. * @return string the generated checkbox tag
  672. * @since 2.0.9
  673. */
  674. protected static function booleanInput($type, $name, $checked = false, $options = [])
  675. {
  676. $options['checked'] = (bool) $checked;
  677. $value = array_key_exists('value', $options) ? $options['value'] : '1';
  678. if (isset($options['uncheck'])) {
  679. // add a hidden field so that if the checkbox is not selected, it still submits a value
  680. $hidden = static::hiddenInput($name, $options['uncheck']);
  681. unset($options['uncheck']);
  682. } else {
  683. $hidden = '';
  684. }
  685. if (isset($options['label'])) {
  686. $label = $options['label'];
  687. $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
  688. unset($options['label'], $options['labelOptions']);
  689. $content = static::label(static::input($type, $name, $value, $options) . ' ' . $label, null, $labelOptions);
  690. return $hidden . $content;
  691. } else {
  692. return $hidden . static::input($type, $name, $value, $options);
  693. }
  694. }
  695. /**
  696. * Generates a drop-down list.
  697. * @param string $name the input name
  698. * @param string $selection the selected value
  699. * @param array $items the option data items. The array keys are option values, and the array values
  700. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  701. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  702. * If you have a list of data models, you may convert them into the format described above using
  703. * [[\yii\helpers\ArrayHelper::map()]].
  704. *
  705. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  706. * the labels will also be HTML-encoded.
  707. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  708. *
  709. * - prompt: string, a prompt text to be displayed as the first option;
  710. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  711. * and the array values are the extra attributes for the corresponding option tags. For example,
  712. *
  713. * ```php
  714. * [
  715. * 'value1' => ['disabled' => true],
  716. * 'value2' => ['label' => 'value 2'],
  717. * ];
  718. * ```
  719. *
  720. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  721. * except that the array keys represent the optgroup labels specified in $items.
  722. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
  723. * Defaults to false.
  724. * - encode: bool, whether to encode option prompt and option value characters.
  725. * Defaults to `true`. This option is available since 2.0.3.
  726. *
  727. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  728. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  729. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  730. *
  731. * @return string the generated drop-down list tag
  732. */
  733. public static function dropDownList($name, $selection = null, $items = [], $options = [])
  734. {
  735. if (!empty($options['multiple'])) {
  736. return static::listBox($name, $selection, $items, $options);
  737. }
  738. $options['name'] = $name;
  739. unset($options['unselect']);
  740. $selectOptions = static::renderSelectOptions($selection, $items, $options);
  741. return static::tag('select', "\n" . $selectOptions . "\n", $options);
  742. }
  743. /**
  744. * Generates a list box.
  745. * @param string $name the input name
  746. * @param string|array $selection the selected value(s)
  747. * @param array $items the option data items. The array keys are option values, and the array values
  748. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  749. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  750. * If you have a list of data models, you may convert them into the format described above using
  751. * [[\yii\helpers\ArrayHelper::map()]].
  752. *
  753. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  754. * the labels will also be HTML-encoded.
  755. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  756. *
  757. * - prompt: string, a prompt text to be displayed as the first option;
  758. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  759. * and the array values are the extra attributes for the corresponding option tags. For example,
  760. *
  761. * ```php
  762. * [
  763. * 'value1' => ['disabled' => true],
  764. * 'value2' => ['label' => 'value 2'],
  765. * ];
  766. * ```
  767. *
  768. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  769. * except that the array keys represent the optgroup labels specified in $items.
  770. * - unselect: string, the value that will be submitted when no option is selected.
  771. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
  772. * mode, we can still obtain the posted unselect value.
  773. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
  774. * Defaults to false.
  775. * - encode: bool, whether to encode option prompt and option value characters.
  776. * Defaults to `true`. This option is available since 2.0.3.
  777. *
  778. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  779. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  780. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  781. *
  782. * @return string the generated list box tag
  783. */
  784. public static function listBox($name, $selection = null, $items = [], $options = [])
  785. {
  786. if (!array_key_exists('size', $options)) {
  787. $options['size'] = 4;
  788. }
  789. if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) {
  790. $name .= '[]';
  791. }
  792. $options['name'] = $name;
  793. if (isset($options['unselect'])) {
  794. // add a hidden field so that if the list box has no option being selected, it still submits a value
  795. if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) {
  796. $name = substr($name, 0, -2);
  797. }
  798. $hidden = static::hiddenInput($name, $options['unselect']);
  799. unset($options['unselect']);
  800. } else {
  801. $hidden = '';
  802. }
  803. $selectOptions = static::renderSelectOptions($selection, $items, $options);
  804. return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
  805. }
  806. /**
  807. * Generates a list of checkboxes.
  808. * A checkbox list allows multiple selection, like [[listBox()]].
  809. * As a result, the corresponding submitted value is an array.
  810. * @param string $name the name attribute of each checkbox.
  811. * @param string|array $selection the selected value(s).
  812. * @param array $items the data item used to generate the checkboxes.
  813. * The array keys are the checkbox values, while the array values are the corresponding labels.
  814. * @param array $options options (name => config) for the checkbox list container tag.
  815. * The following options are specially handled:
  816. *
  817. * - tag: string|false, the tag name of the container element. False to render checkbox without container.
  818. * See also [[tag()]].
  819. * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
  820. * By setting this option, a hidden input will be generated.
  821. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  822. * This option is ignored if `item` option is set.
  823. * - separator: string, the HTML code that separates items.
  824. * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
  825. * - item: callable, a callback that can be used to customize the generation of the HTML code
  826. * corresponding to a single item in $items. The signature of this callback must be:
  827. *
  828. * ```php
  829. * function ($index, $label, $name, $checked, $value)
  830. * ```
  831. *
  832. * where $index is the zero-based index of the checkbox in the whole list; $label
  833. * is the label for the checkbox; and $name, $value and $checked represent the name,
  834. * value and the checked status of the checkbox input, respectively.
  835. *
  836. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  837. *
  838. * @return string the generated checkbox list
  839. */
  840. public static function checkboxList($name, $selection = null, $items = [], $options = [])
  841. {
  842. if (substr($name, -2) !== '[]') {
  843. $name .= '[]';
  844. }
  845. $formatter = ArrayHelper::remove($options, 'item');
  846. $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
  847. $encode = ArrayHelper::remove($options, 'encode', true);
  848. $separator = ArrayHelper::remove($options, 'separator', "\n");
  849. $tag = ArrayHelper::remove($options, 'tag', 'div');
  850. $lines = [];
  851. $index = 0;
  852. foreach ($items as $value => $label) {
  853. $checked = $selection !== null &&
  854. (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
  855. || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn($value, $selection));
  856. if ($formatter !== null) {
  857. $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
  858. } else {
  859. $lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [
  860. 'value' => $value,
  861. 'label' => $encode ? static::encode($label) : $label,
  862. ]));
  863. }
  864. $index++;
  865. }
  866. if (isset($options['unselect'])) {
  867. // add a hidden field so that if the list box has no option being selected, it still submits a value
  868. $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
  869. $hidden = static::hiddenInput($name2, $options['unselect']);
  870. unset($options['unselect']);
  871. } else {
  872. $hidden = '';
  873. }
  874. $visibleContent = implode($separator, $lines);
  875. if ($tag === false) {
  876. return $hidden . $visibleContent;
  877. }
  878. return $hidden . static::tag($tag, $visibleContent, $options);
  879. }
  880. /**
  881. * Generates a list of radio buttons.
  882. * A radio button list is like a checkbox list, except that it only allows single selection.
  883. * @param string $name the name attribute of each radio button.
  884. * @param string|array $selection the selected value(s).
  885. * @param array $items the data item used to generate the radio buttons.
  886. * The array keys are the radio button values, while the array values are the corresponding labels.
  887. * @param array $options options (name => config) for the radio button list container tag.
  888. * The following options are specially handled:
  889. *
  890. * - tag: string|false, the tag name of the container element. False to render radio buttons without container.
  891. * See also [[tag()]].
  892. * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
  893. * By setting this option, a hidden input will be generated.
  894. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  895. * This option is ignored if `item` option is set.
  896. * - separator: string, the HTML code that separates items.
  897. * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
  898. * - item: callable, a callback that can be used to customize the generation of the HTML code
  899. * corresponding to a single item in $items. The signature of this callback must be:
  900. *
  901. * ```php
  902. * function ($index, $label, $name, $checked, $value)
  903. * ```
  904. *
  905. * where $index is the zero-based index of the radio button in the whole list; $label
  906. * is the label for the radio button; and $name, $value and $checked represent the name,
  907. * value and the checked status of the radio button input, respectively.
  908. *
  909. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  910. *
  911. * @return string the generated radio button list
  912. */
  913. public static function radioList($name, $selection = null, $items = [], $options = [])
  914. {
  915. $formatter = ArrayHelper::remove($options, 'item');
  916. $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
  917. $encode = ArrayHelper::remove($options, 'encode', true);
  918. $separator = ArrayHelper::remove($options, 'separator', "\n");
  919. $tag = ArrayHelper::remove($options, 'tag', 'div');
  920. // add a hidden field so that if the list box has no option being selected, it still submits a value
  921. $hidden = isset($options['unselect']) ? static::hiddenInput($name, $options['unselect']) : '';
  922. unset($options['unselect']);
  923. $lines = [];
  924. $index = 0;
  925. foreach ($items as $value => $label) {
  926. $checked = $selection !== null &&
  927. (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
  928. || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn($value, $selection));
  929. if ($formatter !== null) {
  930. $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
  931. } else {
  932. $lines[] = static::radio($name, $checked, array_merge($itemOptions, [
  933. 'value' => $value,
  934. 'label' => $encode ? static::encode($label) : $label,
  935. ]));
  936. }
  937. $index++;
  938. }
  939. $visibleContent = implode($separator, $lines);
  940. if ($tag === false) {
  941. return $hidden . $visibleContent;
  942. }
  943. return $hidden . static::tag($tag, $visibleContent, $options);
  944. }
  945. /**
  946. * Generates an unordered list.
  947. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
  948. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
  949. * @param array $options options (name => config) for the radio button list. The following options are supported:
  950. *
  951. * - encode: boolean, whether to HTML-encode the items. Defaults to true.
  952. * This option is ignored if the `item` option is specified.
  953. * - separator: string, the HTML code that separates items. Defaults to a simple newline (`"\n"`).
  954. * This option is available since version 2.0.7.
  955. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
  956. * - item: callable, a callback that is used to generate each individual list item.
  957. * The signature of this callback must be:
  958. *
  959. * ```php
  960. * function ($item, $index)
  961. * ```
  962. *
  963. * where $index is the array key corresponding to `$item` in `$items`. The callback should return
  964. * the whole list item tag.
  965. *
  966. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  967. *
  968. * @return string the generated unordered list. An empty list tag will be returned if `$items` is empty.
  969. */
  970. public static function ul($items, $options = [])
  971. {
  972. $tag = ArrayHelper::remove($options, 'tag', 'ul');
  973. $encode = ArrayHelper::remove($options, 'encode', true);
  974. $formatter = ArrayHelper::remove($options, 'item');
  975. $separator = ArrayHelper::remove($options, 'separator', "\n");
  976. $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
  977. if (empty($items)) {
  978. return static::tag($tag, '', $options);
  979. }
  980. $results = [];
  981. foreach ($items as $index => $item) {
  982. if ($formatter !== null) {
  983. $results[] = call_user_func($formatter, $item, $index);
  984. } else {
  985. $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
  986. }
  987. }
  988. return static::tag(
  989. $tag,
  990. $separator . implode($separator, $results) . $separator,
  991. $options
  992. );
  993. }
  994. /**
  995. * Generates an ordered list.
  996. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
  997. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
  998. * @param array $options options (name => config) for the radio button list. The following options are supported:
  999. *
  1000. * - encode: boolean, whether to HTML-encode the items. Defaults to true.
  1001. * This option is ignored if the `item` option is specified.
  1002. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
  1003. * - item: callable, a callback that is used to generate each individual list item.
  1004. * The signature of this callback must be:
  1005. *
  1006. * ```php
  1007. * function ($item, $index)
  1008. * ```
  1009. *
  1010. * where $index is the array key corresponding to `$item` in `$items`. The callback should return
  1011. * the whole list item tag.
  1012. *
  1013. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1014. *
  1015. * @return string the generated ordered list. An empty string is returned if `$items` is empty.
  1016. */
  1017. public static function ol($items, $options = [])
  1018. {
  1019. $options['tag'] = 'ol';
  1020. return static::ul($items, $options);
  1021. }
  1022. /**
  1023. * Generates a label tag for the given model attribute.
  1024. * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
  1025. * @param Model $model the model object
  1026. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1027. * about attribute expression.
  1028. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1029. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1030. * If a value is null, the corresponding attribute will not be rendered.
  1031. * The following options are specially handled:
  1032. *
  1033. * - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
  1034. * If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
  1035. * (after encoding).
  1036. *
  1037. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1038. *
  1039. * @return string the generated label tag
  1040. */
  1041. public static function activeLabel($model, $attribute, $options = [])
  1042. {
  1043. $for = ArrayHelper::remove($options, 'for', static::getInputId($model, $attribute));
  1044. $attribute = static::getAttributeName($attribute);
  1045. $label = ArrayHelper::remove($options, 'label', static::encode($model->getAttributeLabel($attribute)));
  1046. return static::label($label, $for, $options);
  1047. }
  1048. /**
  1049. * Generates a hint tag for the given model attribute.
  1050. * The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]].
  1051. * If no hint content can be obtained, method will return an empty string.
  1052. * @param Model $model the model object
  1053. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1054. * about attribute expression.
  1055. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1056. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1057. * If a value is null, the corresponding attribute will not be rendered.
  1058. * The following options are specially handled:
  1059. *
  1060. * - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]].
  1061. * If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display
  1062. * (without encoding).
  1063. *
  1064. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1065. *
  1066. * @return string the generated hint tag
  1067. * @since 2.0.4
  1068. */
  1069. public static function activeHint($model, $attribute, $options = [])
  1070. {
  1071. $attribute = static::getAttributeName($attribute);
  1072. $hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute);
  1073. if (empty($hint)) {
  1074. return '';
  1075. }
  1076. $tag = ArrayHelper::remove($options, 'tag', 'div');
  1077. unset($options['hint']);
  1078. return static::tag($tag, $hint, $options);
  1079. }
  1080. /**
  1081. * Generates a summary of the validation errors.
  1082. * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
  1083. * @param Model|Model[] $models the model(s) whose validation errors are to be displayed
  1084. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1085. *
  1086. * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
  1087. * - footer: string, the footer HTML for the error summary.
  1088. * - encode: boolean, if set to false then the error messages won't be encoded.
  1089. *
  1090. * The rest of the options will be rendered as the attributes of the container tag. The values will
  1091. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1092. * @return string the generated error summary
  1093. */
  1094. public static function errorSummary($models, $options = [])
  1095. {
  1096. $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
  1097. $footer = ArrayHelper::remove($options, 'footer', '');
  1098. $encode = ArrayHelper::remove($options, 'encode', true);
  1099. unset($options['header']);
  1100. $lines = [];
  1101. if (!is_array($models)) {
  1102. $models = [$models];
  1103. }
  1104. foreach ($models as $model) {
  1105. /* @var $model Model */
  1106. foreach ($model->getFirstErrors() as $error) {
  1107. $lines[] = $encode ? Html::encode($error) : $error;
  1108. }
  1109. }
  1110. if (empty($lines)) {
  1111. // still render the placeholder for client-side validation use
  1112. $content = '<ul></ul>';
  1113. $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
  1114. } else {
  1115. $content = '<ul><li>' . implode("</li>\n<li>", $lines) . '</li></ul>';
  1116. }
  1117. return Html::tag('div', $header . $content . $footer, $options);
  1118. }
  1119. /**
  1120. * Generates a tag that contains the first validation error of the specified model attribute.
  1121. * Note that even if there is no validation error, this method will still return an empty error tag.
  1122. * @param Model $model the model object
  1123. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1124. * about attribute expression.
  1125. * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
  1126. * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1127. *
  1128. * The following options are specially handled:
  1129. *
  1130. * - tag: this specifies the tag name. If not set, "div" will be used.
  1131. * See also [[tag()]].
  1132. * - encode: boolean, if set to false then the error message won't be encoded.
  1133. *
  1134. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1135. *
  1136. * @return string the generated label tag
  1137. */
  1138. public static function error($model, $attribute, $options = [])
  1139. {
  1140. $attribute = static::getAttributeName($attribute);
  1141. $error = $model->getFirstError($attribute);
  1142. $tag = ArrayHelper::remove($options, 'tag', 'div');
  1143. $encode = ArrayHelper::remove($options, 'encode', true);
  1144. return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
  1145. }
  1146. /**
  1147. * Generates an input tag for the given model attribute.
  1148. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1149. * unless they are explicitly specified in `$options`.
  1150. * @param string $type the input type (e.g. 'text', 'password')
  1151. * @param Model $model the model object
  1152. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1153. * about attribute expression.
  1154. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1155. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1156. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1157. * @return string the generated input tag
  1158. */
  1159. public static function activeInput($type, $model, $attribute, $options = [])
  1160. {
  1161. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1162. $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
  1163. if (!array_key_exists('id', $options)) {
  1164. $options['id'] = static::getInputId($model, $attribute);
  1165. }
  1166. return static::input($type, $name, $value, $options);
  1167. }
  1168. /**
  1169. * If `maxlength` option is set true and the model attribute is validated by a string validator,
  1170. * the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  1171. * @param Model $model the model object
  1172. * @param string $attribute the attribute name or expression.
  1173. * @param array $options the tag options in terms of name-value pairs.
  1174. */
  1175. private static function normalizeMaxLength($model, $attribute, &$options)
  1176. {
  1177. if (isset($options['maxlength']) && $options['maxlength'] === true) {
  1178. unset($options['maxlength']);
  1179. $attrName = static::getAttributeName($attribute);
  1180. foreach ($model->getActiveValidators($attrName) as $validator) {
  1181. if ($validator instanceof StringValidator && $validator->max !== null) {
  1182. $options['maxlength'] = $validator->max;
  1183. break;
  1184. }
  1185. }
  1186. }
  1187. }
  1188. /**
  1189. * Generates a text input tag for the given model attribute.
  1190. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1191. * unless they are explicitly specified in `$options`.
  1192. * @param Model $model the model object
  1193. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1194. * about attribute expression.
  1195. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1196. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1197. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1198. * The following special options are recognized:
  1199. *
  1200. * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
  1201. * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  1202. * This is available since version 2.0.3.
  1203. *
  1204. * @return string the generated input tag
  1205. */
  1206. public static function activeTextInput($model, $attribute, $options = [])
  1207. {
  1208. self::normalizeMaxLength($model, $attribute, $options);
  1209. return static::activeInput('text', $model, $attribute, $options);
  1210. }
  1211. /**
  1212. * Generates a hidden input tag for the given model attribute.
  1213. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1214. * unless they are explicitly specified in `$options`.
  1215. * @param Model $model the model object
  1216. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1217. * about attribute expression.
  1218. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1219. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1220. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1221. * @return string the generated input tag
  1222. */
  1223. public static function activeHiddenInput($model, $attribute, $options = [])
  1224. {
  1225. return static::activeInput('hidden', $model, $attribute, $options);
  1226. }
  1227. /**
  1228. * Generates a password input tag for the given model attribute.
  1229. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1230. * unless they are explicitly specified in `$options`.
  1231. * @param Model $model the model object
  1232. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1233. * about attribute expression.
  1234. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1235. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1236. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1237. * The following special options are recognized:
  1238. *
  1239. * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
  1240. * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  1241. * This option is available since version 2.0.6.
  1242. *
  1243. * @return string the generated input tag
  1244. */
  1245. public static function activePasswordInput($model, $attribute, $options = [])
  1246. {
  1247. self::normalizeMaxLength($model, $attribute, $options);
  1248. return static::activeInput('password', $model, $attribute, $options);
  1249. }
  1250. /**
  1251. * Generates a file input tag for the given model attribute.
  1252. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1253. * unless they are explicitly specified in `$options`.
  1254. * @param Model $model the model object
  1255. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1256. * about attribute expression.
  1257. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1258. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1259. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1260. * @return string the generated input tag
  1261. */
  1262. public static function activeFileInput($model, $attribute, $options = [])
  1263. {
  1264. // add a hidden field so that if a model only has a file field, we can
  1265. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  1266. $hiddenOptions = ['id' => null, 'value' => ''];
  1267. if (isset($options['name'])) {
  1268. $hiddenOptions['name'] = $options['name'];
  1269. }
  1270. return static::activeHiddenInput($model, $attribute, $hiddenOptions)
  1271. . static::activeInput('file', $model, $attribute, $options);
  1272. }
  1273. /**
  1274. * Generates a textarea tag for the given model attribute.
  1275. * The model attribute value will be used as the content in the textarea.
  1276. * @param Model $model the model object
  1277. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1278. * about attribute expression.
  1279. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1280. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1281. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1282. * The following special options are recognized:
  1283. *
  1284. * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
  1285. * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  1286. * This option is available since version 2.0.6.
  1287. *
  1288. * @return string the generated textarea tag
  1289. */
  1290. public static function activeTextarea($model, $attribute, $options = [])
  1291. {
  1292. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1293. if (isset($options['value'])) {
  1294. $value = $options['value'];
  1295. unset($options['value']);
  1296. } else {
  1297. $value = static::getAttributeValue($model, $attribute);
  1298. }
  1299. if (!array_key_exists('id', $options)) {
  1300. $options['id'] = static::getInputId($model, $attribute);
  1301. }
  1302. self::normalizeMaxLength($model, $attribute, $options);
  1303. return static::textarea($name, $value, $options);
  1304. }
  1305. /**
  1306. * Generates a radio button tag together with a label for the given model attribute.
  1307. * This method will generate the "checked" tag attribute according to the model attribute value.
  1308. * @param Model $model the model object
  1309. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1310. * about attribute expression.
  1311. * @param array $options the tag options in terms of name-value pairs.
  1312. * See [[booleanInput()]] for details about accepted attributes.
  1313. *
  1314. * @return string the generated radio button tag
  1315. */
  1316. public static function activeRadio($model, $attribute, $options = [])
  1317. {
  1318. return static::activeBooleanInput('radio', $model, $attribute, $options);
  1319. }
  1320. /**
  1321. * Generates a checkbox tag together with a label for the given model attribute.
  1322. * This method will generate the "checked" tag attribute according to the model attribute value.
  1323. * @param Model $model the model object
  1324. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1325. * about attribute expression.
  1326. * @param array $options the tag options in terms of name-value pairs.
  1327. * See [[booleanInput()]] for details about accepted attributes.
  1328. *
  1329. * @return string the generated checkbox tag
  1330. */
  1331. public static function activeCheckbox($model, $attribute, $options = [])
  1332. {
  1333. return static::activeBooleanInput('checkbox', $model, $attribute, $options);
  1334. }
  1335. /**
  1336. * Generates a boolean input
  1337. * This method is mainly called by [[activeCheckbox()]] and [[activeRadio()]].
  1338. * @param string $type the input type. This can be either `radio` or `checkbox`.
  1339. * @param Model $model the model object
  1340. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1341. * about attribute expression.
  1342. * @param array $options the tag options in terms of name-value pairs.
  1343. * See [[booleanInput()]] for details about accepted attributes.
  1344. * @return string the generated input element
  1345. * @since 2.0.9
  1346. */
  1347. protected static function activeBooleanInput($type, $model, $attribute, $options = [])
  1348. {
  1349. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1350. $value = static::getAttributeValue($model, $attribute);
  1351. if (!array_key_exists('value', $options)) {
  1352. $options['value'] = '1';
  1353. }
  1354. if (!array_key_exists('uncheck', $options)) {
  1355. $options['uncheck'] = '0';
  1356. }
  1357. if (!array_key_exists('label', $options)) {
  1358. $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
  1359. }
  1360. $checked = "$value" === "{$options['value']}";
  1361. if (!array_key_exists('id', $options)) {
  1362. $options['id'] = static::getInputId($model, $attribute);
  1363. }
  1364. return static::$type($name, $checked, $options);
  1365. }
  1366. /**
  1367. * Generates a drop-down list for the given model attribute.
  1368. * The selection of the drop-down list is taken from the value of the model attribute.
  1369. * @param Model $model the model object
  1370. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1371. * about attribute expression.
  1372. * @param array $items the option data items. The array keys are option values, and the array values
  1373. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  1374. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  1375. * If you have a list of data models, you may convert them into the format described above using
  1376. * [[\yii\helpers\ArrayHelper::map()]].
  1377. *
  1378. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  1379. * the labels will also be HTML-encoded.
  1380. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1381. *
  1382. * - prompt: string, a prompt text to be displayed as the first option;
  1383. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  1384. * and the array values are the extra attributes for the corresponding option tags. For example,
  1385. *
  1386. * ```php
  1387. * [
  1388. * 'value1' => ['disabled' => true],
  1389. * 'value2' => ['label' => 'value 2'],
  1390. * ];
  1391. * ```
  1392. *
  1393. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  1394. * except that the array keys represent the optgroup labels specified in $items.
  1395. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
  1396. * Defaults to false.
  1397. * - encode: bool, whether to encode option prompt and option value characters.
  1398. * Defaults to `true`. This option is available since 2.0.3.
  1399. *
  1400. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  1401. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1402. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1403. *
  1404. * @return string the generated drop-down list tag
  1405. */
  1406. public static function activeDropDownList($model, $attribute, $items, $options = [])
  1407. {
  1408. if (empty($options['multiple'])) {
  1409. return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
  1410. } else {
  1411. return static::activeListBox($model, $attribute, $items, $options);
  1412. }
  1413. }
  1414. /**
  1415. * Generates a list box.
  1416. * The selection of the list box is taken from the value of the model attribute.
  1417. * @param Model $model the model object
  1418. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1419. * about attribute expression.
  1420. * @param array $items the option data items. The array keys are option values, and the array values
  1421. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  1422. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  1423. * If you have a list of data models, you may convert them into the format described above using
  1424. * [[\yii\helpers\ArrayHelper::map()]].
  1425. *
  1426. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  1427. * the labels will also be HTML-encoded.
  1428. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1429. *
  1430. * - prompt: string, a prompt text to be displayed as the first option;
  1431. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  1432. * and the array values are the extra attributes for the corresponding option tags. For example,
  1433. *
  1434. * ```php
  1435. * [
  1436. * 'value1' => ['disabled' => true],
  1437. * 'value2' => ['label' => 'value 2'],
  1438. * ];
  1439. * ```
  1440. *
  1441. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  1442. * except that the array keys represent the optgroup labels specified in $items.
  1443. * - unselect: string, the value that will be submitted when no option is selected.
  1444. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
  1445. * mode, we can still obtain the posted unselect value.
  1446. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
  1447. * Defaults to false.
  1448. * - encode: bool, whether to encode option prompt and option value characters.
  1449. * Defaults to `true`. This option is available since 2.0.3.
  1450. *
  1451. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  1452. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1453. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1454. *
  1455. * @return string the generated list box tag
  1456. */
  1457. public static function activeListBox($model, $attribute, $items, $options = [])
  1458. {
  1459. return static::activeListInput('listBox', $model, $attribute, $items, $options);
  1460. }
  1461. /**
  1462. * Generates a list of checkboxes.
  1463. * A checkbox list allows multiple selection, like [[listBox()]].
  1464. * As a result, the corresponding submitted value is an array.
  1465. * The selection of the checkbox list is taken from the value of the model attribute.
  1466. * @param Model $model the model object
  1467. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1468. * about attribute expression.
  1469. * @param array $items the data item used to generate the checkboxes.
  1470. * The array keys are the checkbox values, and the array values are the corresponding labels.
  1471. * Note that the labels will NOT be HTML-encoded, while the values will.
  1472. * @param array $options options (name => config) for the checkbox list container tag.
  1473. * The following options are specially handled:
  1474. *
  1475. * - tag: string|false, the tag name of the container element. False to render checkbox without container.
  1476. * See also [[tag()]].
  1477. * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
  1478. * You may set this option to be null to prevent default value submission.
  1479. * If this option is not set, an empty string will be submitted.
  1480. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  1481. * This option is ignored if `item` option is set.
  1482. * - separator: string, the HTML code that separates items.
  1483. * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
  1484. * - item: callable, a callback that can be used to customize the generation of the HTML code
  1485. * corresponding to a single item in $items. The signature of this callback must be:
  1486. *
  1487. * ```php
  1488. * function ($index, $label, $name, $checked, $value)
  1489. * ```
  1490. *
  1491. * where $index is the zero-based index of the checkbox in the whole list; $label
  1492. * is the label for the checkbox; and $name, $value and $checked represent the name,
  1493. * value and the checked status of the checkbox input.
  1494. *
  1495. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1496. *
  1497. * @return string the generated checkbox list
  1498. */
  1499. public static function activeCheckboxList($model, $attribute, $items, $options = [])
  1500. {
  1501. return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
  1502. }
  1503. /**
  1504. * Generates a list of radio buttons.
  1505. * A radio button list is like a checkbox list, except that it only allows single selection.
  1506. * The selection of the radio buttons is taken from the value of the model attribute.
  1507. * @param Model $model the model object
  1508. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1509. * about attribute expression.
  1510. * @param array $items the data item used to generate the radio buttons.
  1511. * The array keys are the radio values, and the array values are the corresponding labels.
  1512. * Note that the labels will NOT be HTML-encoded, while the values will.
  1513. * @param array $options options (name => config) for the radio button list container tag.
  1514. * The following options are specially handled:
  1515. *
  1516. * - tag: string|false, the tag name of the container element. False to render radio button without container.
  1517. * See also [[tag()]].
  1518. * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
  1519. * You may set this option to be null to prevent default value submission.
  1520. * If this option is not set, an empty string will be submitted.
  1521. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  1522. * This option is ignored if `item` option is set.
  1523. * - separator: string, the HTML code that separates items.
  1524. * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
  1525. * - item: callable, a callback that can be used to customize the generation of the HTML code
  1526. * corresponding to a single item in $items. The signature of this callback must be:
  1527. *
  1528. * ```php
  1529. * function ($index, $label, $name, $checked, $value)
  1530. * ```
  1531. *
  1532. * where $index is the zero-based index of the radio button in the whole list; $label
  1533. * is the label for the radio button; and $name, $value and $checked represent the name,
  1534. * value and the checked status of the radio button input.
  1535. *
  1536. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1537. *
  1538. * @return string the generated radio button list
  1539. */
  1540. public static function activeRadioList($model, $attribute, $items, $options = [])
  1541. {
  1542. return static::activeListInput('radioList', $model, $attribute, $items, $options);
  1543. }
  1544. /**
  1545. * Generates a list of input fields.
  1546. * This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckBoxList()]].
  1547. * @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'.
  1548. * @param Model $model the model object
  1549. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1550. * about attribute expression.
  1551. * @param array $items the data item used to generate the input fields.
  1552. * The array keys are the input values, and the array values are the corresponding labels.
  1553. * Note that the labels will NOT be HTML-encoded, while the values will.
  1554. * @param array $options options (name => config) for the input list. The supported special options
  1555. * depend on the input type specified by `$type`.
  1556. * @return string the generated input list
  1557. */
  1558. protected static function activeListInput($type, $model, $attribute, $items, $options = [])
  1559. {
  1560. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1561. $selection = static::getAttributeValue($model, $attribute);
  1562. if (!array_key_exists('unselect', $options)) {
  1563. $options['unselect'] = '';
  1564. }
  1565. if (!array_key_exists('id', $options)) {
  1566. $options['id'] = static::getInputId($model, $attribute);
  1567. }
  1568. return static::$type($name, $selection, $items, $options);
  1569. }
  1570. /**
  1571. * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
  1572. * @param string|array $selection the selected value(s). This can be either a string for single selection
  1573. * or an array for multiple selections.
  1574. * @param array $items the option data items. The array keys are option values, and the array values
  1575. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  1576. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  1577. * If you have a list of data models, you may convert them into the format described above using
  1578. * [[\yii\helpers\ArrayHelper::map()]].
  1579. *
  1580. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  1581. * the labels will also be HTML-encoded.
  1582. * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
  1583. * This method will take out these elements, if any: "prompt", "options" and "groups". See more details
  1584. * in [[dropDownList()]] for the explanation of these elements.
  1585. *
  1586. * @return string the generated list options
  1587. */
  1588. public static function renderSelectOptions($selection, $items, &$tagOptions = [])
  1589. {
  1590. $lines = [];
  1591. $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
  1592. $encode = ArrayHelper::remove($tagOptions, 'encode', true);
  1593. if (isset($tagOptions['prompt'])) {
  1594. $prompt = $encode ? static::encode($tagOptions['prompt']) : $tagOptions['prompt'];
  1595. if ($encodeSpaces) {
  1596. $prompt = str_replace(' ', '&nbsp;', $prompt);
  1597. }
  1598. $lines[] = static::tag('option', $prompt, ['value' => '']);
  1599. }
  1600. $options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
  1601. $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
  1602. unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
  1603. $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
  1604. $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
  1605. foreach ($items as $key => $value) {
  1606. if (is_array($value)) {
  1607. $groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
  1608. if (!isset($groupAttrs['label'])) {
  1609. $groupAttrs['label'] = $key;
  1610. }
  1611. $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
  1612. $content = static::renderSelectOptions($selection, $value, $attrs);
  1613. $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
  1614. } else {
  1615. $attrs = isset($options[$key]) ? $options[$key] : [];
  1616. $attrs['value'] = (string) $key;
  1617. if (!array_key_exists('selected', $attrs)) {
  1618. $attrs['selected'] = $selection !== null &&
  1619. (!ArrayHelper::isTraversable($selection) && !strcmp($key, $selection)
  1620. || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn($key, $selection));
  1621. }
  1622. $text = $encode ? static::encode($value) : $value;
  1623. if ($encodeSpaces) {
  1624. $text = str_replace(' ', '&nbsp;', $text);
  1625. }
  1626. $lines[] = static::tag('option', $text, $attrs);
  1627. }
  1628. }
  1629. return implode("\n", $lines);
  1630. }
  1631. /**
  1632. * Renders the HTML tag attributes.
  1633. *
  1634. * Attributes whose values are of boolean type will be treated as
  1635. * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
  1636. *
  1637. * Attributes whose values are null will not be rendered.
  1638. *
  1639. * The values of attributes will be HTML-encoded using [[encode()]].
  1640. *
  1641. * The "data" attribute is specially handled when it is receiving an array value. In this case,
  1642. * the array will be "expanded" and a list data attributes will be rendered. For example,
  1643. * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered:
  1644. * `data-id="1" data-name="yii"`.
  1645. * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as:
  1646. * `data-params='{"id":1,"name":"yii"}' data-status="ok"`.
  1647. *
  1648. * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
  1649. * @return string the rendering result. If the attributes are not empty, they will be rendered
  1650. * into a string with a leading white space (so that it can be directly appended to the tag name
  1651. * in a tag. If there is no attribute, an empty string will be returned.
  1652. */
  1653. public static function renderTagAttributes($attributes)
  1654. {
  1655. if (count($attributes) > 1) {
  1656. $sorted = [];
  1657. foreach (static::$attributeOrder as $name) {
  1658. if (isset($attributes[$name])) {
  1659. $sorted[$name] = $attributes[$name];
  1660. }
  1661. }
  1662. $attributes = array_merge($sorted, $attributes);
  1663. }
  1664. $html = '';
  1665. foreach ($attributes as $name => $value) {
  1666. if (is_bool($value)) {
  1667. if ($value) {
  1668. $html .= " $name";
  1669. }
  1670. } elseif (is_array($value)) {
  1671. if (in_array($name, static::$dataAttributes)) {
  1672. foreach ($value as $n => $v) {
  1673. if (is_array($v)) {
  1674. $html .= " $name-$n='" . Json::htmlEncode($v) . "'";
  1675. } else {
  1676. $html .= " $name-$n=\"" . static::encode($v) . '"';
  1677. }
  1678. }
  1679. } elseif ($name === 'class') {
  1680. if (empty($value)) {
  1681. continue;
  1682. }
  1683. $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
  1684. } elseif ($name === 'style') {
  1685. if (empty($value)) {
  1686. continue;
  1687. }
  1688. $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
  1689. } else {
  1690. $html .= " $name='" . Json::htmlEncode($value) . "'";
  1691. }
  1692. } elseif ($value !== null) {
  1693. $html .= " $name=\"" . static::encode($value) . '"';
  1694. }
  1695. }
  1696. return $html;
  1697. }
  1698. /**
  1699. * Adds a CSS class (or several classes) to the specified options.
  1700. * If the CSS class is already in the options, it will not be added again.
  1701. * If class specification at given options is an array, and some class placed there with the named (string) key,
  1702. * overriding of such key will have no effect. For example:
  1703. *
  1704. * ```php
  1705. * $options = ['class' => ['persistent' => 'initial']];
  1706. * Html::addCssClass($options, ['persistent' => 'override']);
  1707. * var_dump($options['class']); // outputs: array('persistent' => 'initial');
  1708. * ```
  1709. *
  1710. * @param array $options the options to be modified.
  1711. * @param string|array $class the CSS class(es) to be added
  1712. */
  1713. public static function addCssClass(&$options, $class)
  1714. {
  1715. if (isset($options['class'])) {
  1716. if (is_array($options['class'])) {
  1717. $options['class'] = self::mergeCssClasses($options['class'], (array) $class);
  1718. } else {
  1719. $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
  1720. $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
  1721. }
  1722. } else {
  1723. $options['class'] = $class;
  1724. }
  1725. }
  1726. /**
  1727. * Merges already existing CSS classes with new one.
  1728. * This method provides the priority for named existing classes over additional.
  1729. * @param array $existingClasses already existing CSS classes.
  1730. * @param array $additionalClasses CSS classes to be added.
  1731. * @return array merge result.
  1732. */
  1733. private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
  1734. {
  1735. foreach ($additionalClasses as $key => $class) {
  1736. if (is_int($key) && !in_array($class, $existingClasses)) {
  1737. $existingClasses[] = $class;
  1738. } elseif (!isset($existingClasses[$key])) {
  1739. $existingClasses[$key] = $class;
  1740. }
  1741. }
  1742. return array_unique($existingClasses);
  1743. }
  1744. /**
  1745. * Removes a CSS class from the specified options.
  1746. * @param array $options the options to be modified.
  1747. * @param string|array $class the CSS class(es) to be removed
  1748. */
  1749. public static function removeCssClass(&$options, $class)
  1750. {
  1751. if (isset($options['class'])) {
  1752. if (is_array($options['class'])) {
  1753. $classes = array_diff($options['class'], (array) $class);
  1754. if (empty($classes)) {
  1755. unset($options['class']);
  1756. } else {
  1757. $options['class'] = $classes;
  1758. }
  1759. } else {
  1760. $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
  1761. $classes = array_diff($classes, (array) $class);
  1762. if (empty($classes)) {
  1763. unset($options['class']);
  1764. } else {
  1765. $options['class'] = implode(' ', $classes);
  1766. }
  1767. }
  1768. }
  1769. }
  1770. /**
  1771. * Adds the specified CSS style to the HTML options.
  1772. *
  1773. * If the options already contain a `style` element, the new style will be merged
  1774. * with the existing one. If a CSS property exists in both the new and the old styles,
  1775. * the old one may be overwritten if `$overwrite` is true.
  1776. *
  1777. * For example,
  1778. *
  1779. * ```php
  1780. * Html::addCssStyle($options, 'width: 100px; height: 200px');
  1781. * ```
  1782. *
  1783. * @param array $options the HTML options to be modified.
  1784. * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
  1785. * array (e.g. `['width' => '100px', 'height' => '200px']`).
  1786. * @param boolean $overwrite whether to overwrite existing CSS properties if the new style
  1787. * contain them too.
  1788. * @see removeCssStyle()
  1789. * @see cssStyleFromArray()
  1790. * @see cssStyleToArray()
  1791. */
  1792. public static function addCssStyle(&$options, $style, $overwrite = true)
  1793. {
  1794. if (!empty($options['style'])) {
  1795. $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
  1796. $newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
  1797. if (!$overwrite) {
  1798. foreach ($newStyle as $property => $value) {
  1799. if (isset($oldStyle[$property])) {
  1800. unset($newStyle[$property]);
  1801. }
  1802. }
  1803. }
  1804. $style = array_merge($oldStyle, $newStyle);
  1805. }
  1806. $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
  1807. }
  1808. /**
  1809. * Removes the specified CSS style from the HTML options.
  1810. *
  1811. * For example,
  1812. *
  1813. * ```php
  1814. * Html::removeCssStyle($options, ['width', 'height']);
  1815. * ```
  1816. *
  1817. * @param array $options the HTML options to be modified.
  1818. * @param string|array $properties the CSS properties to be removed. You may use a string
  1819. * if you are removing a single property.
  1820. * @see addCssStyle()
  1821. */
  1822. public static function removeCssStyle(&$options, $properties)
  1823. {
  1824. if (!empty($options['style'])) {
  1825. $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
  1826. foreach ((array) $properties as $property) {
  1827. unset($style[$property]);
  1828. }
  1829. $options['style'] = static::cssStyleFromArray($style);
  1830. }
  1831. }
  1832. /**
  1833. * Converts a CSS style array into a string representation.
  1834. *
  1835. * For example,
  1836. *
  1837. * ```php
  1838. * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
  1839. * // will display: 'width: 100px; height: 200px;'
  1840. * ```
  1841. *
  1842. * @param array $style the CSS style array. The array keys are the CSS property names,
  1843. * and the array values are the corresponding CSS property values.
  1844. * @return string the CSS style string. If the CSS style is empty, a null will be returned.
  1845. */
  1846. public static function cssStyleFromArray(array $style)
  1847. {
  1848. $result = '';
  1849. foreach ($style as $name => $value) {
  1850. $result .= "$name: $value; ";
  1851. }
  1852. // return null if empty to avoid rendering the "style" attribute
  1853. return $result === '' ? null : rtrim($result);
  1854. }
  1855. /**
  1856. * Converts a CSS style string into an array representation.
  1857. *
  1858. * The array keys are the CSS property names, and the array values
  1859. * are the corresponding CSS property values.
  1860. *
  1861. * For example,
  1862. *
  1863. * ```php
  1864. * print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
  1865. * // will display: ['width' => '100px', 'height' => '200px']
  1866. * ```
  1867. *
  1868. * @param string $style the CSS style string
  1869. * @return array the array representation of the CSS style
  1870. */
  1871. public static function cssStyleToArray($style)
  1872. {
  1873. $result = [];
  1874. foreach (explode(';', $style) as $property) {
  1875. $property = explode(':', $property);
  1876. if (count($property) > 1) {
  1877. $result[trim($property[0])] = trim($property[1]);
  1878. }
  1879. }
  1880. return $result;
  1881. }
  1882. /**
  1883. * Returns the real attribute name from the given attribute expression.
  1884. *
  1885. * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
  1886. * It is mainly used in tabular data input and/or input of array type. Below are some examples:
  1887. *
  1888. * - `[0]content` is used in tabular data input to represent the "content" attribute
  1889. * for the first model in tabular input;
  1890. * - `dates[0]` represents the first array element of the "dates" attribute;
  1891. * - `[0]dates[0]` represents the first array element of the "dates" attribute
  1892. * for the first model in tabular input.
  1893. *
  1894. * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
  1895. * @param string $attribute the attribute name or expression
  1896. * @return string the attribute name without prefix and suffix.
  1897. * @throws InvalidParamException if the attribute name contains non-word characters.
  1898. */
  1899. public static function getAttributeName($attribute)
  1900. {
  1901. if (preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
  1902. return $matches[2];
  1903. } else {
  1904. throw new InvalidParamException('Attribute name must contain word characters only.');
  1905. }
  1906. }
  1907. /**
  1908. * Returns the value of the specified attribute name or expression.
  1909. *
  1910. * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
  1911. * See [[getAttributeName()]] for more details about attribute expression.
  1912. *
  1913. * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
  1914. * the primary value(s) of the AR instance(s) will be returned instead.
  1915. *
  1916. * @param Model $model the model object
  1917. * @param string $attribute the attribute name or expression
  1918. * @return string|array the corresponding attribute value
  1919. * @throws InvalidParamException if the attribute name contains non-word characters.
  1920. */
  1921. public static function getAttributeValue($model, $attribute)
  1922. {
  1923. if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
  1924. throw new InvalidParamException('Attribute name must contain word characters only.');
  1925. }
  1926. $attribute = $matches[2];
  1927. $value = $model->$attribute;
  1928. if ($matches[3] !== '') {
  1929. foreach (explode('][', trim($matches[3], '[]')) as $id) {
  1930. if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
  1931. $value = $value[$id];
  1932. } else {
  1933. return null;
  1934. }
  1935. }
  1936. }
  1937. // https://github.com/yiisoft/yii2/issues/1457
  1938. if (is_array($value)) {
  1939. foreach ($value as $i => $v) {
  1940. if ($v instanceof ActiveRecordInterface) {
  1941. $v = $v->getPrimaryKey(false);
  1942. $value[$i] = is_array($v) ? json_encode($v) : $v;
  1943. }
  1944. }
  1945. } elseif ($value instanceof ActiveRecordInterface) {
  1946. $value = $value->getPrimaryKey(false);
  1947. return is_array($value) ? json_encode($value) : $value;
  1948. }
  1949. return $value;
  1950. }
  1951. /**
  1952. * Generates an appropriate input name for the specified attribute name or expression.
  1953. *
  1954. * This method generates a name that can be used as the input name to collect user input
  1955. * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
  1956. * of the model and the given attribute name. For example, if the form name of the `Post` model
  1957. * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
  1958. *
  1959. * See [[getAttributeName()]] for explanation of attribute expression.
  1960. *
  1961. * @param Model $model the model object
  1962. * @param string $attribute the attribute name or expression
  1963. * @return string the generated input name
  1964. * @throws InvalidParamException if the attribute name contains non-word characters.
  1965. */
  1966. public static function getInputName($model, $attribute)
  1967. {
  1968. $formName = $model->formName();
  1969. if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
  1970. throw new InvalidParamException('Attribute name must contain word characters only.');
  1971. }
  1972. $prefix = $matches[1];
  1973. $attribute = $matches[2];
  1974. $suffix = $matches[3];
  1975. if ($formName === '' && $prefix === '') {
  1976. return $attribute . $suffix;
  1977. } elseif ($formName !== '') {
  1978. return $formName . $prefix . "[$attribute]" . $suffix;
  1979. } else {
  1980. throw new InvalidParamException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
  1981. }
  1982. }
  1983. /**
  1984. * Generates an appropriate input ID for the specified attribute name or expression.
  1985. *
  1986. * This method converts the result [[getInputName()]] into a valid input ID.
  1987. * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
  1988. * @param Model $model the model object
  1989. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
  1990. * @return string the generated input ID
  1991. * @throws InvalidParamException if the attribute name contains non-word characters.
  1992. */
  1993. public static function getInputId($model, $attribute)
  1994. {
  1995. $name = strtolower(static::getInputName($model, $attribute));
  1996. return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
  1997. }
  1998. /**
  1999. * Escapes regular expression to use in JavaScript
  2000. * @param string $regexp the regular expression to be escaped.
  2001. * @return string the escaped result.
  2002. * @since 2.0.6
  2003. */
  2004. public static function escapeJsRegularExpression($regexp)
  2005. {
  2006. $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
  2007. $deliminator = substr($pattern, 0, 1);
  2008. $pos = strrpos($pattern, $deliminator, 1);
  2009. $flag = substr($pattern, $pos + 1);
  2010. if ($deliminator !== '/') {
  2011. $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
  2012. } else {
  2013. $pattern = substr($pattern, 0, $pos + 1);
  2014. }
  2015. if (!empty($flag)) {
  2016. $pattern .= preg_replace('/[^igm]/', '', $flag);
  2017. }
  2018. return $pattern;
  2019. }
  2020. }