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

1963 line
94KB

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