BaseHtml.php 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657
  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\web\Request;
  12. use yii\base\Model;
  13. /**
  14. * BaseHtml provides concrete implementation for [[Html]].
  15. *
  16. * Do not use BaseHtml. Use [[Html]] instead.
  17. *
  18. * @author Qiang Xue <[email protected]>
  19. * @since 2.0
  20. */
  21. class BaseHtml
  22. {
  23. /**
  24. * @var array list of void elements (element name => 1)
  25. * @see http://www.w3.org/TR/html-markup/syntax.html#void-element
  26. */
  27. public static $voidElements = [
  28. 'area' => 1,
  29. 'base' => 1,
  30. 'br' => 1,
  31. 'col' => 1,
  32. 'command' => 1,
  33. 'embed' => 1,
  34. 'hr' => 1,
  35. 'img' => 1,
  36. 'input' => 1,
  37. 'keygen' => 1,
  38. 'link' => 1,
  39. 'meta' => 1,
  40. 'param' => 1,
  41. 'source' => 1,
  42. 'track' => 1,
  43. 'wbr' => 1,
  44. ];
  45. /**
  46. * @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes
  47. * that are rendered by [[renderTagAttributes()]].
  48. */
  49. public static $attributeOrder = [
  50. 'type',
  51. 'id',
  52. 'class',
  53. 'name',
  54. 'value',
  55. 'href',
  56. 'src',
  57. 'action',
  58. 'method',
  59. 'selected',
  60. 'checked',
  61. 'readonly',
  62. 'disabled',
  63. 'multiple',
  64. 'size',
  65. 'maxlength',
  66. 'width',
  67. 'height',
  68. 'rows',
  69. 'cols',
  70. 'alt',
  71. 'title',
  72. 'rel',
  73. 'media',
  74. ];
  75. /**
  76. * Encodes special characters into HTML entities.
  77. * The [[yii\base\Application::charset|application charset]] will be used for encoding.
  78. * @param string $content the content to be encoded
  79. * @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false,
  80. * HTML entities in `$content` will not be further encoded.
  81. * @return string the encoded content
  82. * @see decode()
  83. * @see http://www.php.net/manual/en/function.htmlspecialchars.php
  84. */
  85. public static function encode($content, $doubleEncode = true)
  86. {
  87. return htmlspecialchars($content, ENT_QUOTES, Yii::$app->charset, $doubleEncode);
  88. }
  89. /**
  90. * Decodes special HTML entities back to the corresponding characters.
  91. * This is the opposite of [[encode()]].
  92. * @param string $content the content to be decoded
  93. * @return string the decoded content
  94. * @see encode()
  95. * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
  96. */
  97. public static function decode($content)
  98. {
  99. return htmlspecialchars_decode($content, ENT_QUOTES);
  100. }
  101. /**
  102. * Generates a complete HTML tag.
  103. * @param string $name the tag name
  104. * @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded.
  105. * If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks.
  106. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  107. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  108. * If a value is null, the corresponding attribute will not be rendered.
  109. * @return string the generated HTML tag
  110. * @see beginTag()
  111. * @see endTag()
  112. */
  113. public static function tag($name, $content = '', $options = [])
  114. {
  115. $html = "<$name" . static::renderTagAttributes($options) . '>';
  116. return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>";
  117. }
  118. /**
  119. * Generates a start tag.
  120. * @param string $name the tag name
  121. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  122. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  123. * If a value is null, the corresponding attribute will not be rendered.
  124. * @return string the generated start tag
  125. * @see endTag()
  126. * @see tag()
  127. */
  128. public static function beginTag($name, $options = [])
  129. {
  130. return "<$name" . static::renderTagAttributes($options) . '>';
  131. }
  132. /**
  133. * Generates an end tag.
  134. * @param string $name the tag name
  135. * @return string the generated end tag
  136. * @see beginTag()
  137. * @see tag()
  138. */
  139. public static function endTag($name)
  140. {
  141. return "</$name>";
  142. }
  143. /**
  144. * Generates a style tag.
  145. * @param string $content the style content
  146. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  147. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  148. * If a value is null, the corresponding attribute will not be rendered.
  149. * If the options does not contain "type", a "type" attribute with value "text/css" will be used.
  150. * @return string the generated style tag
  151. */
  152. public static function style($content, $options = [])
  153. {
  154. return static::tag('style', $content, $options);
  155. }
  156. /**
  157. * Generates a script tag.
  158. * @param string $content the script content
  159. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  160. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  161. * If a value is null, the corresponding attribute will not be rendered.
  162. * If the options does not contain "type", a "type" attribute with value "text/javascript" will be rendered.
  163. * @return string the generated script tag
  164. */
  165. public static function script($content, $options = [])
  166. {
  167. return static::tag('script', $content, $options);
  168. }
  169. /**
  170. * Generates a link tag that refers to an external CSS file.
  171. * @param array|string $url the URL of the external CSS file. This parameter will be processed by [[url()]].
  172. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  173. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  174. * If a value is null, the corresponding attribute will not be rendered.
  175. * @return string the generated link tag
  176. * @see url()
  177. */
  178. public static function cssFile($url, $options = [])
  179. {
  180. if (!isset($options['rel'])) {
  181. $options['rel'] = 'stylesheet';
  182. }
  183. $options['href'] = static::url($url);
  184. return static::tag('link', '', $options);
  185. }
  186. /**
  187. * Generates a script tag that refers to an external JavaScript file.
  188. * @param string $url the URL of the external JavaScript file. This parameter will be processed by [[url()]].
  189. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  190. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  191. * If a value is null, the corresponding attribute will not be rendered.
  192. * @return string the generated script tag
  193. * @see url()
  194. */
  195. public static function jsFile($url, $options = [])
  196. {
  197. $options['src'] = static::url($url);
  198. return static::tag('script', '', $options);
  199. }
  200. /**
  201. * Generates a form start tag.
  202. * @param array|string $action the form action URL. This parameter will be processed by [[url()]].
  203. * @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive).
  204. * Since most browsers only support "post" and "get", if other methods are given, they will
  205. * be simulated using "post", and a hidden input will be added which contains the actual method type.
  206. * See [[\yii\web\Request::restVar]] for more details.
  207. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  208. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  209. * If a value is null, the corresponding attribute will not be rendered.
  210. * @return string the generated form start tag.
  211. * @see endForm()
  212. */
  213. public static function beginForm($action = '', $method = 'post', $options = [])
  214. {
  215. $action = static::url($action);
  216. $hiddenInputs = [];
  217. $request = Yii::$app->getRequest();
  218. if ($request instanceof Request) {
  219. if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) {
  220. // simulate PUT, DELETE, etc. via POST
  221. $hiddenInputs[] = static::hiddenInput($request->restVar, $method);
  222. $method = 'post';
  223. }
  224. if ($request->enableCsrfValidation && !strcasecmp($method, 'post')) {
  225. $hiddenInputs[] = static::hiddenInput($request->csrfVar, $request->getCsrfToken());
  226. }
  227. }
  228. if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) {
  229. // query parameters in the action are ignored for GET method
  230. // we use hidden fields to add them back
  231. foreach (explode('&', substr($action, $pos + 1)) as $pair) {
  232. if (($pos1 = strpos($pair, '=')) !== false) {
  233. $hiddenInputs[] = static::hiddenInput(
  234. urldecode(substr($pair, 0, $pos1)),
  235. urldecode(substr($pair, $pos1 + 1))
  236. );
  237. } else {
  238. $hiddenInputs[] = static::hiddenInput(urldecode($pair), '');
  239. }
  240. }
  241. $action = substr($action, 0, $pos);
  242. }
  243. $options['action'] = $action;
  244. $options['method'] = $method;
  245. $form = static::beginTag('form', $options);
  246. if (!empty($hiddenInputs)) {
  247. $form .= "\n" . implode("\n", $hiddenInputs);
  248. }
  249. return $form;
  250. }
  251. /**
  252. * Generates a form end tag.
  253. * @return string the generated tag
  254. * @see beginForm()
  255. */
  256. public static function endForm()
  257. {
  258. return '</form>';
  259. }
  260. /**
  261. * Generates a hyperlink tag.
  262. * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
  263. * such as an image tag. If this is coming from end users, you should consider [[encode()]]
  264. * it to prevent XSS attacks.
  265. * @param array|string|null $url the URL for the hyperlink tag. This parameter will be processed by [[url()]]
  266. * and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute
  267. * will not be generated.
  268. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  269. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  270. * If a value is null, the corresponding attribute will not be rendered.
  271. * @return string the generated hyperlink
  272. * @see url()
  273. */
  274. public static function a($text, $url = null, $options = [])
  275. {
  276. if ($url !== null) {
  277. $options['href'] = static::url($url);
  278. }
  279. return static::tag('a', $text, $options);
  280. }
  281. /**
  282. * Generates a mailto hyperlink.
  283. * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
  284. * such as an image tag. If this is coming from end users, you should consider [[encode()]]
  285. * it to prevent XSS attacks.
  286. * @param string $email email address. If this is null, the first parameter (link body) will be treated
  287. * as the email address and used.
  288. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  289. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  290. * If a value is null, the corresponding attribute will not be rendered.
  291. * @return string the generated mailto link
  292. */
  293. public static function mailto($text, $email = null, $options = [])
  294. {
  295. $options['href'] = 'mailto:' . ($email === null ? $text : $email);
  296. return static::tag('a', $text, $options);
  297. }
  298. /**
  299. * Generates an image tag.
  300. * @param string $src the image URL. This parameter will be processed by [[url()]].
  301. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  302. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  303. * If a value is null, the corresponding attribute will not be rendered.
  304. * @return string the generated image tag
  305. */
  306. public static function img($src, $options = [])
  307. {
  308. $options['src'] = static::url($src);
  309. if (!isset($options['alt'])) {
  310. $options['alt'] = '';
  311. }
  312. return static::tag('img', '', $options);
  313. }
  314. /**
  315. * Generates a label tag.
  316. * @param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code
  317. * such as an image tag. If this is is coming from end users, you should [[encode()]]
  318. * it to prevent XSS attacks.
  319. * @param string $for the ID of the HTML element that this label is associated with.
  320. * If this is null, the "for" attribute will not be generated.
  321. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  322. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  323. * If a value is null, the corresponding attribute will not be rendered.
  324. * @return string the generated label tag
  325. */
  326. public static function label($content, $for = null, $options = [])
  327. {
  328. $options['for'] = $for;
  329. return static::tag('label', $content, $options);
  330. }
  331. /**
  332. * Generates a button tag.
  333. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
  334. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
  335. * you should consider [[encode()]] it to prevent XSS attacks.
  336. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  337. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  338. * If a value is null, the corresponding attribute will not be rendered.
  339. * @return string the generated button tag
  340. */
  341. public static function button($content = 'Button', $options = [])
  342. {
  343. return static::tag('button', $content, $options);
  344. }
  345. /**
  346. * Generates a submit button tag.
  347. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
  348. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
  349. * you should consider [[encode()]] it to prevent XSS attacks.
  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. * @return string the generated submit button tag
  354. */
  355. public static function submitButton($content = 'Submit', $options = [])
  356. {
  357. $options['type'] = 'submit';
  358. return static::button($content, $options);
  359. }
  360. /**
  361. * Generates a reset button tag.
  362. * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
  363. * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
  364. * you should consider [[encode()]] it to prevent XSS attacks.
  365. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  366. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  367. * If a value is null, the corresponding attribute will not be rendered.
  368. * @return string the generated reset button tag
  369. */
  370. public static function resetButton($content = 'Reset', $options = [])
  371. {
  372. $options['type'] = 'reset';
  373. return static::button($content, $options);
  374. }
  375. /**
  376. * Generates an input type of the given type.
  377. * @param string $type the type attribute.
  378. * @param string $name the name attribute. If it is null, the name attribute will not be generated.
  379. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  380. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  381. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  382. * If a value is null, the corresponding attribute will not be rendered.
  383. * @return string the generated input tag
  384. */
  385. public static function input($type, $name = null, $value = null, $options = [])
  386. {
  387. $options['type'] = $type;
  388. $options['name'] = $name;
  389. $options['value'] = $value === null ? null : (string)$value;
  390. return static::tag('input', '', $options);
  391. }
  392. /**
  393. * Generates an input button.
  394. * @param string $label the value attribute. If it is null, the value attribute will not be generated.
  395. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  396. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  397. * If a value is null, the corresponding attribute will not be rendered.
  398. * @return string the generated button tag
  399. */
  400. public static function buttonInput($label = 'Button', $options = [])
  401. {
  402. $options['type'] = 'button';
  403. $options['value'] = $label;
  404. return static::tag('input', '', $options);
  405. }
  406. /**
  407. * Generates a submit input button.
  408. * @param string $label the value attribute. If it is null, the value attribute will not be generated.
  409. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  410. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  411. * If a value is null, the corresponding attribute will not be rendered.
  412. * @return string the generated button tag
  413. */
  414. public static function submitInput($label = 'Submit', $options = [])
  415. {
  416. $options['type'] = 'submit';
  417. $options['value'] = $label;
  418. return static::tag('input', '', $options);
  419. }
  420. /**
  421. * Generates a reset input button.
  422. * @param string $label the value attribute. If it is null, the value attribute will not be generated.
  423. * @param array $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]].
  424. * Attributes whose value is null will be ignored and not put in the tag returned.
  425. * @return string the generated button tag
  426. */
  427. public static function resetInput($label = 'Reset', $options = [])
  428. {
  429. $options['type'] = 'reset';
  430. $options['value'] = $label;
  431. return static::tag('input', '', $options);
  432. }
  433. /**
  434. * Generates a text input field.
  435. * @param string $name the name attribute.
  436. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  437. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  438. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  439. * If a value is null, the corresponding attribute will not be rendered.
  440. * @return string the generated button tag
  441. */
  442. public static function textInput($name, $value = null, $options = [])
  443. {
  444. return static::input('text', $name, $value, $options);
  445. }
  446. /**
  447. * Generates a hidden input field.
  448. * @param string $name the name attribute.
  449. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  450. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  451. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  452. * If a value is null, the corresponding attribute will not be rendered.
  453. * @return string the generated button tag
  454. */
  455. public static function hiddenInput($name, $value = null, $options = [])
  456. {
  457. return static::input('hidden', $name, $value, $options);
  458. }
  459. /**
  460. * Generates a password input field.
  461. * @param string $name the name attribute.
  462. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  463. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  464. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  465. * If a value is null, the corresponding attribute will not be rendered.
  466. * @return string the generated button tag
  467. */
  468. public static function passwordInput($name, $value = null, $options = [])
  469. {
  470. return static::input('password', $name, $value, $options);
  471. }
  472. /**
  473. * Generates a file input field.
  474. * To use a file input field, you should set the enclosing form's "enctype" attribute to
  475. * be "multipart/form-data". After the form is submitted, the uploaded file information
  476. * can be obtained via $_FILES[$name] (see PHP documentation).
  477. * @param string $name the name attribute.
  478. * @param string $value the value attribute. If it is null, the value attribute will not be generated.
  479. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  480. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  481. * If a value is null, the corresponding attribute will not be rendered.
  482. * @return string the generated button tag
  483. */
  484. public static function fileInput($name, $value = null, $options = [])
  485. {
  486. return static::input('file', $name, $value, $options);
  487. }
  488. /**
  489. * Generates a text area input.
  490. * @param string $name the input name
  491. * @param string $value the input value. Note that it will be encoded using [[encode()]].
  492. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  493. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  494. * If a value is null, the corresponding attribute will not be rendered.
  495. * @return string the generated text area tag
  496. */
  497. public static function textarea($name, $value = '', $options = [])
  498. {
  499. $options['name'] = $name;
  500. return static::tag('textarea', static::encode($value), $options);
  501. }
  502. /**
  503. * Generates a radio button input.
  504. * @param string $name the name attribute.
  505. * @param boolean $checked whether the radio button should be checked.
  506. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  507. *
  508. * - uncheck: string, the value associated with the uncheck state of the radio button. When this attribute
  509. * is present, a hidden input will be generated so that if the radio button is not checked and is submitted,
  510. * the value of this attribute will still be submitted to the server via the hidden input.
  511. * - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
  512. * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
  513. * When this option is specified, the radio button will be enclosed by a label tag.
  514. * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
  515. * - container: array|boolean, the HTML attributes for the container tag. This is only used when the "label" option is specified.
  516. * If it is false, no container will be rendered. If it is an array or not, a "div" container will be rendered
  517. * around the the radio button.
  518. *
  519. * The rest of the options will be rendered as the attributes of the resulting radio button tag. The values will
  520. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  521. *
  522. * @return string the generated radio button tag
  523. */
  524. public static function radio($name, $checked = false, $options = [])
  525. {
  526. $options['checked'] = (boolean)$checked;
  527. $value = array_key_exists('value', $options) ? $options['value'] : '1';
  528. if (isset($options['uncheck'])) {
  529. // add a hidden field so that if the radio button is not selected, it still submits a value
  530. $hidden = static::hiddenInput($name, $options['uncheck']);
  531. unset($options['uncheck']);
  532. } else {
  533. $hidden = '';
  534. }
  535. if (isset($options['label'])) {
  536. $label = $options['label'];
  537. $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
  538. $container = isset($options['container']) ? $options['container'] : ['class' => 'radio'];
  539. unset($options['label'], $options['labelOptions'], $options['container']);
  540. $content = static::label(static::input('radio', $name, $value, $options) . ' ' . $label, null, $labelOptions);
  541. if (is_array($container)) {
  542. return $hidden . static::tag('div', $content, $container);
  543. } else {
  544. return $hidden . $content;
  545. }
  546. } else {
  547. return $hidden . static::input('radio', $name, $value, $options);
  548. }
  549. }
  550. /**
  551. * Generates a checkbox input.
  552. * @param string $name the name attribute.
  553. * @param boolean $checked whether the checkbox should be checked.
  554. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  555. *
  556. * - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute
  557. * is present, a hidden input will be generated so that if the checkbox is not checked and is submitted,
  558. * the value of this attribute will still be submitted to the server via the hidden input.
  559. * - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
  560. * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
  561. * When this option is specified, the checkbox will be enclosed by a label tag.
  562. * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
  563. * - container: array|boolean, the HTML attributes for the container tag. This is only used when the "label" option is specified.
  564. * If it is false, no container will be rendered. If it is an array or not, a "div" container will be rendered
  565. * around the the radio button.
  566. *
  567. * The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will
  568. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  569. *
  570. * @return string the generated checkbox tag
  571. */
  572. public static function checkbox($name, $checked = false, $options = [])
  573. {
  574. $options['checked'] = (boolean)$checked;
  575. $value = array_key_exists('value', $options) ? $options['value'] : '1';
  576. if (isset($options['uncheck'])) {
  577. // add a hidden field so that if the checkbox is not selected, it still submits a value
  578. $hidden = static::hiddenInput($name, $options['uncheck']);
  579. unset($options['uncheck']);
  580. } else {
  581. $hidden = '';
  582. }
  583. if (isset($options['label'])) {
  584. $label = $options['label'];
  585. $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
  586. $container = isset($options['container']) ? $options['container'] : ['class' => 'checkbox'];
  587. unset($options['label'], $options['labelOptions'], $options['container']);
  588. $content = static::label(static::input('checkbox', $name, $value, $options) . ' ' . $label, null, $labelOptions);
  589. if (is_array($container)) {
  590. return $hidden . static::tag('div', $content, $container);
  591. } else {
  592. return $hidden . $content;
  593. }
  594. } else {
  595. return $hidden . static::input('checkbox', $name, $value, $options);
  596. }
  597. }
  598. /**
  599. * Generates a drop-down list.
  600. * @param string $name the input name
  601. * @param string $selection the selected value
  602. * @param array $items the option data items. The array keys are option values, and the array values
  603. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  604. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  605. * If you have a list of data models, you may convert them into the format described above using
  606. * [[\yii\helpers\ArrayHelper::map()]].
  607. *
  608. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  609. * the labels will also be HTML-encoded.
  610. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  611. *
  612. * - prompt: string, a prompt text to be displayed as the first option;
  613. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  614. * and the array values are the extra attributes for the corresponding option tags. For example,
  615. *
  616. * ~~~
  617. * [
  618. * 'value1' => ['disabled' => true],
  619. * 'value2' => ['label' => 'value 2'],
  620. * ];
  621. * ~~~
  622. *
  623. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  624. * except that the array keys represent the optgroup labels specified in $items.
  625. *
  626. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  627. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  628. *
  629. * @return string the generated drop-down list tag
  630. */
  631. public static function dropDownList($name, $selection = null, $items = [], $options = [])
  632. {
  633. if (!empty($options['multiple'])) {
  634. return static::listBox($name, $selection, $items, $options);
  635. }
  636. $options['name'] = $name;
  637. $selectOptions = static::renderSelectOptions($selection, $items, $options);
  638. return static::tag('select', "\n" . $selectOptions . "\n", $options);
  639. }
  640. /**
  641. * Generates a list box.
  642. * @param string $name the input name
  643. * @param string|array $selection the selected value(s)
  644. * @param array $items the option data items. The array keys are option values, and the array values
  645. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  646. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  647. * If you have a list of data models, you may convert them into the format described above using
  648. * [[\yii\helpers\ArrayHelper::map()]].
  649. *
  650. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  651. * the labels will also be HTML-encoded.
  652. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  653. *
  654. * - prompt: string, a prompt text to be displayed as the first option;
  655. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  656. * and the array values are the extra attributes for the corresponding option tags. For example,
  657. *
  658. * ~~~
  659. * [
  660. * 'value1' => ['disabled' => true],
  661. * 'value2' => ['label' => 'value 2'],
  662. * ];
  663. * ~~~
  664. *
  665. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  666. * except that the array keys represent the optgroup labels specified in $items.
  667. * - unselect: string, the value that will be submitted when no option is selected.
  668. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
  669. * mode, we can still obtain the posted unselect value.
  670. *
  671. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  672. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  673. *
  674. * @return string the generated list box tag
  675. */
  676. public static function listBox($name, $selection = null, $items = [], $options = [])
  677. {
  678. if (!array_key_exists('size', $options)) {
  679. $options['size'] = 4;
  680. }
  681. if (!empty($options['multiple']) && substr($name, -2) !== '[]') {
  682. $name .= '[]';
  683. }
  684. $options['name'] = $name;
  685. if (isset($options['unselect'])) {
  686. // add a hidden field so that if the list box has no option being selected, it still submits a value
  687. if (substr($name, -2) === '[]') {
  688. $name = substr($name, 0, -2);
  689. }
  690. $hidden = static::hiddenInput($name, $options['unselect']);
  691. unset($options['unselect']);
  692. } else {
  693. $hidden = '';
  694. }
  695. $selectOptions = static::renderSelectOptions($selection, $items, $options);
  696. return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
  697. }
  698. /**
  699. * Generates a list of checkboxes.
  700. * A checkbox list allows multiple selection, like [[listBox()]].
  701. * As a result, the corresponding submitted value is an array.
  702. * @param string $name the name attribute of each checkbox.
  703. * @param string|array $selection the selected value(s).
  704. * @param array $items the data item used to generate the checkboxes.
  705. * The array values are the labels, while the array keys are the corresponding checkbox values.
  706. * @param array $options options (name => config) for the checkbox list container tag.
  707. * The following options are specially handled:
  708. *
  709. * - tag: string, the tag name of the container element.
  710. * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
  711. * By setting this option, a hidden input will be generated.
  712. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  713. * This option is ignored if `item` option is set.
  714. * - separator: string, the HTML code that separates items.
  715. * - itemOptions: array, the options for generating the radio button tag using [[checkbox()]].
  716. * - item: callable, a callback that can be used to customize the generation of the HTML code
  717. * corresponding to a single item in $items. The signature of this callback must be:
  718. *
  719. * ~~~
  720. * function ($index, $label, $name, $checked, $value)
  721. * ~~~
  722. *
  723. * where $index is the zero-based index of the checkbox in the whole list; $label
  724. * is the label for the checkbox; and $name, $value and $checked represent the name,
  725. * value and the checked status of the checkbox input, respectively.
  726. * @return string the generated checkbox list
  727. */
  728. public static function checkboxList($name, $selection = null, $items = [], $options = [])
  729. {
  730. if (substr($name, -2) !== '[]') {
  731. $name .= '[]';
  732. }
  733. $formatter = isset($options['item']) ? $options['item'] : null;
  734. $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
  735. $encode = !isset($options['encode']) || $options['encode'];
  736. $lines = [];
  737. $index = 0;
  738. foreach ($items as $value => $label) {
  739. $checked = $selection !== null &&
  740. (!is_array($selection) && !strcmp($value, $selection)
  741. || is_array($selection) && in_array($value, $selection));
  742. if ($formatter !== null) {
  743. $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
  744. } else {
  745. $lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [
  746. 'value' => $value,
  747. 'label' => $encode ? static::encode($label) : $label,
  748. ]));
  749. }
  750. $index++;
  751. }
  752. if (isset($options['unselect'])) {
  753. // add a hidden field so that if the list box has no option being selected, it still submits a value
  754. $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
  755. $hidden = static::hiddenInput($name2, $options['unselect']);
  756. } else {
  757. $hidden = '';
  758. }
  759. $separator = isset($options['separator']) ? $options['separator'] : "\n";
  760. $tag = isset($options['tag']) ? $options['tag'] : 'div';
  761. unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']);
  762. return $hidden . static::tag($tag, implode($separator, $lines), $options);
  763. }
  764. /**
  765. * Generates a list of radio buttons.
  766. * A radio button list is like a checkbox list, except that it only allows single selection.
  767. * @param string $name the name attribute of each radio button.
  768. * @param string|array $selection the selected value(s).
  769. * @param array $items the data item used to generate the radio buttons.
  770. * The array values are the labels, while the array keys are the corresponding radio button values.
  771. * @param array $options options (name => config) for the radio button list. The following options are supported:
  772. *
  773. * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
  774. * By setting this option, a hidden input will be generated.
  775. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  776. * This option is ignored if `item` option is set.
  777. * - separator: string, the HTML code that separates items.
  778. * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
  779. * - item: callable, a callback that can be used to customize the generation of the HTML code
  780. * corresponding to a single item in $items. The signature of this callback must be:
  781. *
  782. * ~~~
  783. * function ($index, $label, $name, $checked, $value)
  784. * ~~~
  785. *
  786. * where $index is the zero-based index of the radio button in the whole list; $label
  787. * is the label for the radio button; and $name, $value and $checked represent the name,
  788. * value and the checked status of the radio button input, respectively.
  789. * @return string the generated radio button list
  790. */
  791. public static function radioList($name, $selection = null, $items = [], $options = [])
  792. {
  793. $encode = !isset($options['encode']) || $options['encode'];
  794. $formatter = isset($options['item']) ? $options['item'] : null;
  795. $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
  796. $lines = [];
  797. $index = 0;
  798. foreach ($items as $value => $label) {
  799. $checked = $selection !== null &&
  800. (!is_array($selection) && !strcmp($value, $selection)
  801. || is_array($selection) && in_array($value, $selection));
  802. if ($formatter !== null) {
  803. $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
  804. } else {
  805. $lines[] = static::radio($name, $checked, array_merge($itemOptions, [
  806. 'value' => $value,
  807. 'label' => $encode ? static::encode($label) : $label,
  808. ]));
  809. }
  810. $index++;
  811. }
  812. $separator = isset($options['separator']) ? $options['separator'] : "\n";
  813. if (isset($options['unselect'])) {
  814. // add a hidden field so that if the list box has no option being selected, it still submits a value
  815. $hidden = static::hiddenInput($name, $options['unselect']);
  816. } else {
  817. $hidden = '';
  818. }
  819. $tag = isset($options['tag']) ? $options['tag'] : 'div';
  820. unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']);
  821. return $hidden . static::tag($tag, implode($separator, $lines), $options);
  822. }
  823. /**
  824. * Generates an unordered list.
  825. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
  826. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
  827. * @param array $options options (name => config) for the radio button list. The following options are supported:
  828. *
  829. * - encode: boolean, whether to HTML-encode the items. Defaults to true.
  830. * This option is ignored if the `item` option is specified.
  831. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
  832. * - item: callable, a callback that is used to generate each individual list item.
  833. * The signature of this callback must be:
  834. *
  835. * ~~~
  836. * function ($item, $index)
  837. * ~~~
  838. *
  839. * where $index is the array key corresponding to `$item` in `$items`. The callback should return
  840. * the whole list item tag.
  841. *
  842. * @return string the generated unordered list. An empty string is returned if `$items` is empty.
  843. */
  844. public static function ul($items, $options = [])
  845. {
  846. if (empty($items)) {
  847. return '';
  848. }
  849. $tag = isset($options['tag']) ? $options['tag'] : 'ul';
  850. $encode = !isset($options['encode']) || $options['encode'];
  851. $formatter = isset($options['item']) ? $options['item'] : null;
  852. $itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
  853. unset($options['tag'], $options['encode'], $options['item'], $options['itemOptions']);
  854. $results = [];
  855. foreach ($items as $index => $item) {
  856. if ($formatter !== null) {
  857. $results[] = call_user_func($formatter, $item, $index);
  858. } else {
  859. $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
  860. }
  861. }
  862. return static::tag($tag, "\n" . implode("\n", $results) . "\n", $options);
  863. }
  864. /**
  865. * Generates an ordered list.
  866. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
  867. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
  868. * @param array $options options (name => config) for the radio button list. The following options are supported:
  869. *
  870. * - encode: boolean, whether to HTML-encode the items. Defaults to true.
  871. * This option is ignored if the `item` option is specified.
  872. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
  873. * - item: callable, a callback that is used to generate each individual list item.
  874. * The signature of this callback must be:
  875. *
  876. * ~~~
  877. * function ($item, $index)
  878. * ~~~
  879. *
  880. * where $index is the array key corresponding to `$item` in `$items`. The callback should return
  881. * the whole list item tag.
  882. *
  883. * @return string the generated ordered list. An empty string is returned if `$items` is empty.
  884. */
  885. public static function ol($items, $options = [])
  886. {
  887. $options['tag'] = 'ol';
  888. return static::ul($items, $options);
  889. }
  890. /**
  891. * Generates a label tag for the given model attribute.
  892. * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
  893. * @param Model $model the model object
  894. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  895. * about attribute expression.
  896. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  897. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  898. * If a value is null, the corresponding attribute will not be rendered.
  899. * The following options are specially handled:
  900. *
  901. * - label: this specifies the label to be displayed. Note that this will NOT be [[encoded()]].
  902. * If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
  903. * (after encoding).
  904. *
  905. * @return string the generated label tag
  906. */
  907. public static function activeLabel($model, $attribute, $options = [])
  908. {
  909. $for = array_key_exists('for', $options) ? $options['for'] : static::getInputId($model, $attribute);
  910. $attribute = static::getAttributeName($attribute);
  911. $label = isset($options['label']) ? $options['label'] : static::encode($model->getAttributeLabel($attribute));
  912. unset($options['label'], $options['for']);
  913. return static::label($label, $for, $options);
  914. }
  915. /**
  916. * Generates a tag that contains the first validation error of the specified model attribute.
  917. * Note that even if there is no validation error, this method will still return an empty error tag.
  918. * @param Model $model the model object
  919. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  920. * about attribute expression.
  921. * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
  922. * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  923. *
  924. * The following options are specially handled:
  925. *
  926. * - tag: this specifies the tag name. If not set, "div" will be used.
  927. *
  928. * @return string the generated label tag
  929. */
  930. public static function error($model, $attribute, $options = [])
  931. {
  932. $attribute = static::getAttributeName($attribute);
  933. $error = $model->getFirstError($attribute);
  934. $tag = isset($options['tag']) ? $options['tag'] : 'div';
  935. unset($options['tag']);
  936. return Html::tag($tag, Html::encode($error), $options);
  937. }
  938. /**
  939. * Generates an input tag for the given model attribute.
  940. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  941. * unless they are explicitly specified in `$options`.
  942. * @param string $type the input type (e.g. 'text', 'password')
  943. * @param Model $model the model object
  944. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  945. * about attribute expression.
  946. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  947. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  948. * @return string the generated input tag
  949. */
  950. public static function activeInput($type, $model, $attribute, $options = [])
  951. {
  952. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  953. $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
  954. if (!array_key_exists('id', $options)) {
  955. $options['id'] = static::getInputId($model, $attribute);
  956. }
  957. return static::input($type, $name, $value, $options);
  958. }
  959. /**
  960. * Generates a text input tag for the given model attribute.
  961. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  962. * unless they are explicitly specified in `$options`.
  963. * @param Model $model the model object
  964. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  965. * about attribute expression.
  966. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  967. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  968. * @return string the generated input tag
  969. */
  970. public static function activeTextInput($model, $attribute, $options = [])
  971. {
  972. return static::activeInput('text', $model, $attribute, $options);
  973. }
  974. /**
  975. * Generates a hidden input tag for the given model attribute.
  976. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  977. * unless they are explicitly specified in `$options`.
  978. * @param Model $model the model object
  979. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  980. * about attribute expression.
  981. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  982. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  983. * @return string the generated input tag
  984. */
  985. public static function activeHiddenInput($model, $attribute, $options = [])
  986. {
  987. return static::activeInput('hidden', $model, $attribute, $options);
  988. }
  989. /**
  990. * Generates a password input tag for the given model attribute.
  991. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  992. * unless they are explicitly specified in `$options`.
  993. * @param Model $model the model object
  994. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  995. * about attribute expression.
  996. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  997. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  998. * @return string the generated input tag
  999. */
  1000. public static function activePasswordInput($model, $attribute, $options = [])
  1001. {
  1002. return static::activeInput('password', $model, $attribute, $options);
  1003. }
  1004. /**
  1005. * Generates a file input tag for the given model attribute.
  1006. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1007. * unless they are explicitly specified in `$options`.
  1008. * @param Model $model the model object
  1009. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1010. * about attribute expression.
  1011. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1012. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1013. * @return string the generated input tag
  1014. */
  1015. public static function activeFileInput($model, $attribute, $options = [])
  1016. {
  1017. // add a hidden field so that if a model only has a file field, we can
  1018. // still use isset($_POST[$modelClass]) to detect if the input is submitted
  1019. return static::activeHiddenInput($model, $attribute, ['id' => null, 'value' => ''])
  1020. . static::activeInput('file', $model, $attribute, $options);
  1021. }
  1022. /**
  1023. * Generates a textarea tag for the given model attribute.
  1024. * The model attribute value will be used as the content in the textarea.
  1025. * @param Model $model the model object
  1026. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1027. * about attribute expression.
  1028. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1029. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1030. * @return string the generated textarea tag
  1031. */
  1032. public static function activeTextarea($model, $attribute, $options = [])
  1033. {
  1034. $name = static::getInputName($model, $attribute);
  1035. $value = static::getAttributeValue($model, $attribute);
  1036. if (!array_key_exists('id', $options)) {
  1037. $options['id'] = static::getInputId($model, $attribute);
  1038. }
  1039. return static::textarea($name, $value, $options);
  1040. }
  1041. /**
  1042. * Generates a radio button tag for the given model attribute.
  1043. * This method will generate the "checked" tag attribute according to the model attribute value.
  1044. * @param Model $model the model object
  1045. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1046. * about attribute expression.
  1047. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1048. *
  1049. * - uncheck: string, the value associated with the uncheck state of the radio button. If not set,
  1050. * it will take the default value '0'. This method will render a hidden input so that if the radio button
  1051. * is not checked and is submitted, the value of this attribute will still be submitted to the server
  1052. * via the hidden input.
  1053. * - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
  1054. * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
  1055. * When this option is specified, the radio button will be enclosed by a label tag.
  1056. * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
  1057. *
  1058. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  1059. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1060. *
  1061. * @return string the generated radio button tag
  1062. */
  1063. public static function activeRadio($model, $attribute, $options = [])
  1064. {
  1065. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1066. $value = static::getAttributeValue($model, $attribute);
  1067. if (!array_key_exists('value', $options)) {
  1068. $options['value'] = '1';
  1069. }
  1070. if (!array_key_exists('uncheck', $options)) {
  1071. $options['uncheck'] = '0';
  1072. }
  1073. $checked = "$value" === "{$options['value']}";
  1074. if (!array_key_exists('id', $options)) {
  1075. $options['id'] = static::getInputId($model, $attribute);
  1076. }
  1077. return static::radio($name, $checked, $options);
  1078. }
  1079. /**
  1080. * Generates a checkbox tag for the given model attribute.
  1081. * This method will generate the "checked" tag attribute according to the model attribute value.
  1082. * @param Model $model the model object
  1083. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1084. * about attribute expression.
  1085. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1086. *
  1087. * - uncheck: string, the value associated with the uncheck state of the radio button. If not set,
  1088. * it will take the default value '0'. This method will render a hidden input so that if the radio button
  1089. * is not checked and is submitted, the value of this attribute will still be submitted to the server
  1090. * via the hidden input.
  1091. * - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
  1092. * in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
  1093. * When this option is specified, the checkbox will be enclosed by a label tag.
  1094. * - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
  1095. *
  1096. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  1097. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1098. *
  1099. * @return string the generated checkbox tag
  1100. */
  1101. public static function activeCheckbox($model, $attribute, $options = [])
  1102. {
  1103. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1104. $value = static::getAttributeValue($model, $attribute);
  1105. if (!array_key_exists('value', $options)) {
  1106. $options['value'] = '1';
  1107. }
  1108. if (!array_key_exists('uncheck', $options)) {
  1109. $options['uncheck'] = '0';
  1110. }
  1111. $checked = "$value" === "{$options['value']}";
  1112. if (!array_key_exists('id', $options)) {
  1113. $options['id'] = static::getInputId($model, $attribute);
  1114. }
  1115. return static::checkbox($name, $checked, $options);
  1116. }
  1117. /**
  1118. * Generates a drop-down list for the given model attribute.
  1119. * The selection of the drop-down list is taken from the value of the model attribute.
  1120. * @param Model $model the model object
  1121. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1122. * about attribute expression.
  1123. * @param array $items the option data items. The array keys are option values, and the array values
  1124. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  1125. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  1126. * If you have a list of data models, you may convert them into the format described above using
  1127. * [[\yii\helpers\ArrayHelper::map()]].
  1128. *
  1129. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  1130. * the labels will also be HTML-encoded.
  1131. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1132. *
  1133. * - prompt: string, a prompt text to be displayed as the first option;
  1134. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  1135. * and the array values are the extra attributes for the corresponding option tags. For example,
  1136. *
  1137. * ~~~
  1138. * [
  1139. * 'value1' => ['disabled' => true],
  1140. * 'value2' => ['label' => 'value 2'],
  1141. * ];
  1142. * ~~~
  1143. *
  1144. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  1145. * except that the array keys represent the optgroup labels specified in $items.
  1146. *
  1147. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  1148. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1149. *
  1150. * @return string the generated drop-down list tag
  1151. */
  1152. public static function activeDropDownList($model, $attribute, $items, $options = [])
  1153. {
  1154. if (!empty($options['multiple'])) {
  1155. return static::activeListBox($model, $attribute, $items, $options);
  1156. }
  1157. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1158. $selection = static::getAttributeValue($model, $attribute);
  1159. if (!array_key_exists('id', $options)) {
  1160. $options['id'] = static::getInputId($model, $attribute);
  1161. }
  1162. return static::dropDownList($name, $selection, $items, $options);
  1163. }
  1164. /**
  1165. * Generates a list box.
  1166. * The selection of the list box is taken from the value of the model attribute.
  1167. * @param Model $model the model object
  1168. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1169. * about attribute expression.
  1170. * @param array $items the option data items. The array keys are option values, and the array values
  1171. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  1172. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  1173. * If you have a list of data models, you may convert them into the format described above using
  1174. * [[\yii\helpers\ArrayHelper::map()]].
  1175. *
  1176. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  1177. * the labels will also be HTML-encoded.
  1178. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1179. *
  1180. * - prompt: string, a prompt text to be displayed as the first option;
  1181. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  1182. * and the array values are the extra attributes for the corresponding option tags. For example,
  1183. *
  1184. * ~~~
  1185. * [
  1186. * 'value1' => ['disabled' => true],
  1187. * 'value2' => ['label' => 'value 2'],
  1188. * ];
  1189. * ~~~
  1190. *
  1191. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  1192. * except that the array keys represent the optgroup labels specified in $items.
  1193. * - unselect: string, the value that will be submitted when no option is selected.
  1194. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
  1195. * mode, we can still obtain the posted unselect value.
  1196. *
  1197. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  1198. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1199. *
  1200. * @return string the generated list box tag
  1201. */
  1202. public static function activeListBox($model, $attribute, $items, $options = [])
  1203. {
  1204. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1205. $selection = static::getAttributeValue($model, $attribute);
  1206. if (!array_key_exists('unselect', $options)) {
  1207. $options['unselect'] = '';
  1208. }
  1209. if (!array_key_exists('id', $options)) {
  1210. $options['id'] = static::getInputId($model, $attribute);
  1211. }
  1212. return static::listBox($name, $selection, $items, $options);
  1213. }
  1214. /**
  1215. * Generates a list of checkboxes.
  1216. * A checkbox list allows multiple selection, like [[listBox()]].
  1217. * As a result, the corresponding submitted value is an array.
  1218. * The selection of the checkbox list is taken from the value of the model attribute.
  1219. * @param Model $model the model object
  1220. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1221. * about attribute expression.
  1222. * @param array $items the data item used to generate the checkboxes.
  1223. * The array values are the labels, while the array keys are the corresponding checkbox values.
  1224. * Note that the labels will NOT be HTML-encoded, while the values will.
  1225. * @param array $options options (name => config) for the checkbox list. The following options are specially handled:
  1226. *
  1227. * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
  1228. * You may set this option to be null to prevent default value submission.
  1229. * If this option is not set, an empty string will be submitted.
  1230. * - separator: string, the HTML code that separates items.
  1231. * - item: callable, a callback that can be used to customize the generation of the HTML code
  1232. * corresponding to a single item in $items. The signature of this callback must be:
  1233. *
  1234. * ~~~
  1235. * function ($index, $label, $name, $checked, $value)
  1236. * ~~~
  1237. *
  1238. * where $index is the zero-based index of the checkbox in the whole list; $label
  1239. * is the label for the checkbox; and $name, $value and $checked represent the name,
  1240. * value and the checked status of the checkbox input.
  1241. * @return string the generated checkbox list
  1242. */
  1243. public static function activeCheckboxList($model, $attribute, $items, $options = [])
  1244. {
  1245. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1246. $selection = static::getAttributeValue($model, $attribute);
  1247. if (!array_key_exists('unselect', $options)) {
  1248. $options['unselect'] = '';
  1249. }
  1250. if (!array_key_exists('id', $options)) {
  1251. $options['id'] = static::getInputId($model, $attribute);
  1252. }
  1253. return static::checkboxList($name, $selection, $items, $options);
  1254. }
  1255. /**
  1256. * Generates a list of radio buttons.
  1257. * A radio button list is like a checkbox list, except that it only allows single selection.
  1258. * The selection of the radio buttons is taken from the value of the model attribute.
  1259. * @param Model $model the model object
  1260. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1261. * about attribute expression.
  1262. * @param array $items the data item used to generate the radio buttons.
  1263. * The array keys are the labels, while the array values are the corresponding radio button values.
  1264. * Note that the labels will NOT be HTML-encoded, while the values will.
  1265. * @param array $options options (name => config) for the radio button list. The following options are specially handled:
  1266. *
  1267. * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
  1268. * You may set this option to be null to prevent default value submission.
  1269. * If this option is not set, an empty string will be submitted.
  1270. * - separator: string, the HTML code that separates items.
  1271. * - item: callable, a callback that can be used to customize the generation of the HTML code
  1272. * corresponding to a single item in $items. The signature of this callback must be:
  1273. *
  1274. * ~~~
  1275. * function ($index, $label, $name, $checked, $value)
  1276. * ~~~
  1277. *
  1278. * where $index is the zero-based index of the radio button in the whole list; $label
  1279. * is the label for the radio button; and $name, $value and $checked represent the name,
  1280. * value and the checked status of the radio button input.
  1281. * @return string the generated radio button list
  1282. */
  1283. public static function activeRadioList($model, $attribute, $items, $options = [])
  1284. {
  1285. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1286. $selection = static::getAttributeValue($model, $attribute);
  1287. if (!array_key_exists('unselect', $options)) {
  1288. $options['unselect'] = '';
  1289. }
  1290. if (!array_key_exists('id', $options)) {
  1291. $options['id'] = static::getInputId($model, $attribute);
  1292. }
  1293. return static::radioList($name, $selection, $items, $options);
  1294. }
  1295. /**
  1296. * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
  1297. * @param string|array $selection the selected value(s). This can be either a string for single selection
  1298. * or an array for multiple selections.
  1299. * @param array $items the option data items. The array keys are option values, and the array values
  1300. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  1301. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  1302. * If you have a list of data models, you may convert them into the format described above using
  1303. * [[\yii\helpers\ArrayHelper::map()]].
  1304. *
  1305. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  1306. * the labels will also be HTML-encoded.
  1307. * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
  1308. * This method will take out these elements, if any: "prompt", "options" and "groups". See more details
  1309. * in [[dropDownList()]] for the explanation of these elements.
  1310. *
  1311. * @return string the generated list options
  1312. */
  1313. public static function renderSelectOptions($selection, $items, &$tagOptions = [])
  1314. {
  1315. $lines = [];
  1316. if (isset($tagOptions['prompt'])) {
  1317. $prompt = str_replace(' ', '&nbsp;', static::encode($tagOptions['prompt']));
  1318. $lines[] = static::tag('option', $prompt, ['value' => '']);
  1319. }
  1320. $options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
  1321. $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
  1322. unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
  1323. foreach ($items as $key => $value) {
  1324. if (is_array($value)) {
  1325. $groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
  1326. $groupAttrs['label'] = $key;
  1327. $attrs = ['options' => $options, 'groups' => $groups];
  1328. $content = static::renderSelectOptions($selection, $value, $attrs);
  1329. $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
  1330. } else {
  1331. $attrs = isset($options[$key]) ? $options[$key] : [];
  1332. $attrs['value'] = (string)$key;
  1333. $attrs['selected'] = $selection !== null &&
  1334. (!is_array($selection) && !strcmp($key, $selection)
  1335. || is_array($selection) && in_array($key, $selection));
  1336. $lines[] = static::tag('option', str_replace(' ', '&nbsp;', static::encode($value)), $attrs);
  1337. }
  1338. }
  1339. return implode("\n", $lines);
  1340. }
  1341. /**
  1342. * Renders the HTML tag attributes.
  1343. * Attributes whose values are of boolean type will be treated as
  1344. * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
  1345. * And attributes whose values are null will not be rendered.
  1346. * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
  1347. * @return string the rendering result. If the attributes are not empty, they will be rendered
  1348. * into a string with a leading white space (so that it can be directly appended to the tag name
  1349. * in a tag. If there is no attribute, an empty string will be returned.
  1350. */
  1351. public static function renderTagAttributes($attributes)
  1352. {
  1353. if (count($attributes) > 1) {
  1354. $sorted = [];
  1355. foreach (static::$attributeOrder as $name) {
  1356. if (isset($attributes[$name])) {
  1357. $sorted[$name] = $attributes[$name];
  1358. }
  1359. }
  1360. $attributes = array_merge($sorted, $attributes);
  1361. }
  1362. $html = '';
  1363. foreach ($attributes as $name => $value) {
  1364. if (is_bool($value)) {
  1365. if ($value) {
  1366. $html .= " $name";
  1367. }
  1368. } elseif ($value !== null) {
  1369. $html .= " $name=\"" . static::encode($value) . '"';
  1370. }
  1371. }
  1372. return $html;
  1373. }
  1374. /**
  1375. * Normalizes the input parameter to be a valid URL.
  1376. *
  1377. * If the input parameter
  1378. *
  1379. * - is an empty string: the currently requested URL will be returned;
  1380. * - is a non-empty string: it will first be processed by [[Yii::getAlias()]]. If the result
  1381. * is an absolute URL, it will be returned without any change further; Otherwise, the result
  1382. * will be prefixed with [[\yii\web\Request::baseUrl]] and returned.
  1383. * - is an array: the first array element is considered a route, while the rest of the name-value
  1384. * pairs are treated as the parameters to be used for URL creation using [[\yii\web\Controller::createUrl()]].
  1385. * For example: `['post/index', 'page' => 2]`, `['index']`.
  1386. * In case there is no controller, [[\yii\web\UrlManager::createUrl()]] will be used.
  1387. *
  1388. * @param array|string $url the parameter to be used to generate a valid URL
  1389. * @return string the normalized URL
  1390. * @throws InvalidParamException if the parameter is invalid.
  1391. */
  1392. public static function url($url)
  1393. {
  1394. if (is_array($url)) {
  1395. if (isset($url[0])) {
  1396. $route = $url[0];
  1397. $params = array_splice($url, 1);
  1398. if (Yii::$app->controller instanceof \yii\web\Controller) {
  1399. return Yii::$app->controller->createUrl($route, $params);
  1400. } else {
  1401. return Yii::$app->getUrlManager()->createUrl($route, $params);
  1402. }
  1403. } else {
  1404. throw new InvalidParamException('The array specifying a URL must contain at least one element.');
  1405. }
  1406. } elseif ($url === '') {
  1407. return Yii::$app->getRequest()->getUrl();
  1408. } else {
  1409. $url = Yii::getAlias($url);
  1410. if ($url !== '' && ($url[0] === '/' || $url[0] === '#' || strpos($url, '://') || !strncmp($url, './', 2))) {
  1411. return $url;
  1412. } else {
  1413. return Yii::$app->getRequest()->getBaseUrl() . '/' . $url;
  1414. }
  1415. }
  1416. }
  1417. /**
  1418. * Adds a CSS class to the specified options.
  1419. * If the CSS class is already in the options, it will not be added again.
  1420. * @param array $options the options to be modified.
  1421. * @param string $class the CSS class to be added
  1422. */
  1423. public static function addCssClass(&$options, $class)
  1424. {
  1425. if (isset($options['class'])) {
  1426. $classes = ' ' . $options['class'] . ' ';
  1427. if (($pos = strpos($classes, ' ' . $class . ' ')) === false) {
  1428. $options['class'] .= ' ' . $class;
  1429. }
  1430. } else {
  1431. $options['class'] = $class;
  1432. }
  1433. }
  1434. /**
  1435. * Removes a CSS class from the specified options.
  1436. * @param array $options the options to be modified.
  1437. * @param string $class the CSS class to be removed
  1438. */
  1439. public static function removeCssClass(&$options, $class)
  1440. {
  1441. if (isset($options['class'])) {
  1442. $classes = array_unique(preg_split('/\s+/', $options['class'] . ' ' . $class, -1, PREG_SPLIT_NO_EMPTY));
  1443. if (($index = array_search($class, $classes)) !== false) {
  1444. unset($classes[$index]);
  1445. }
  1446. if (empty($classes)) {
  1447. unset($options['class']);
  1448. } else {
  1449. $options['class'] = implode(' ', $classes);
  1450. }
  1451. }
  1452. }
  1453. /**
  1454. * Returns the real attribute name from the given attribute expression.
  1455. *
  1456. * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
  1457. * It is mainly used in tabular data input and/or input of array type. Below are some examples:
  1458. *
  1459. * - `[0]content` is used in tabular data input to represent the "content" attribute
  1460. * for the first model in tabular input;
  1461. * - `dates[0]` represents the first array element of the "dates" attribute;
  1462. * - `[0]dates[0]` represents the first array element of the "dates" attribute
  1463. * for the first model in tabular input.
  1464. *
  1465. * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
  1466. * @param string $attribute the attribute name or expression
  1467. * @return string the attribute name without prefix and suffix.
  1468. * @throws InvalidParamException if the attribute name contains non-word characters.
  1469. */
  1470. public static function getAttributeName($attribute)
  1471. {
  1472. if (preg_match('/(^|.*\])(\w+)(\[.*|$)/', $attribute, $matches)) {
  1473. return $matches[2];
  1474. } else {
  1475. throw new InvalidParamException('Attribute name must contain word characters only.');
  1476. }
  1477. }
  1478. /**
  1479. * Returns the value of the specified attribute name or expression.
  1480. *
  1481. * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
  1482. * See [[getAttributeName()]] for more details about attribute expression.
  1483. *
  1484. * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
  1485. * the primary value(s) of the AR instance(s) will be returned instead.
  1486. *
  1487. * @param Model $model the model object
  1488. * @param string $attribute the attribute name or expression
  1489. * @return string|array the corresponding attribute value
  1490. * @throws InvalidParamException if the attribute name contains non-word characters.
  1491. */
  1492. public static function getAttributeValue($model, $attribute)
  1493. {
  1494. if (!preg_match('/(^|.*\])(\w+)(\[.*|$)/', $attribute, $matches)) {
  1495. throw new InvalidParamException('Attribute name must contain word characters only.');
  1496. }
  1497. $attribute = $matches[2];
  1498. $value = $model->$attribute;
  1499. if ($matches[3] !== '') {
  1500. foreach (explode('][', trim($matches[3], '[]')) as $id) {
  1501. if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
  1502. $value = $value[$id];
  1503. } else {
  1504. return null;
  1505. }
  1506. }
  1507. }
  1508. // https://github.com/yiisoft/yii2/issues/1457
  1509. if (is_array($value)) {
  1510. foreach ($value as $i => $v) {
  1511. if ($v instanceof ActiveRecordInterface) {
  1512. $v = $v->getPrimaryKey(false);
  1513. $value[$i] = is_array($v) ? json_encode($v) : $v;
  1514. }
  1515. }
  1516. } elseif ($value instanceof ActiveRecordInterface) {
  1517. $value = $value->getPrimaryKey(false);
  1518. return is_array($value) ? json_encode($value) : $value;
  1519. }
  1520. return $value;
  1521. }
  1522. /**
  1523. * Generates an appropriate input name for the specified attribute name or expression.
  1524. *
  1525. * This method generates a name that can be used as the input name to collect user input
  1526. * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
  1527. * of the model and the given attribute name. For example, if the form name of the `Post` model
  1528. * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
  1529. *
  1530. * See [[getAttributeName()]] for explanation of attribute expression.
  1531. *
  1532. * @param Model $model the model object
  1533. * @param string $attribute the attribute name or expression
  1534. * @return string the generated input name
  1535. * @throws InvalidParamException if the attribute name contains non-word characters.
  1536. */
  1537. public static function getInputName($model, $attribute)
  1538. {
  1539. $formName = $model->formName();
  1540. if (!preg_match('/(^|.*\])(\w+)(\[.*|$)/', $attribute, $matches)) {
  1541. throw new InvalidParamException('Attribute name must contain word characters only.');
  1542. }
  1543. $prefix = $matches[1];
  1544. $attribute = $matches[2];
  1545. $suffix = $matches[3];
  1546. if ($formName === '' && $prefix === '') {
  1547. return $attribute . $suffix;
  1548. } elseif ($formName !== '') {
  1549. return $formName . $prefix . "[$attribute]" . $suffix;
  1550. } else {
  1551. throw new InvalidParamException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
  1552. }
  1553. }
  1554. /**
  1555. * Generates an appropriate input ID for the specified attribute name or expression.
  1556. *
  1557. * This method converts the result [[getInputName()]] into a valid input ID.
  1558. * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
  1559. * @param Model $model the model object
  1560. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
  1561. * @return string the generated input ID
  1562. * @throws InvalidParamException if the attribute name contains non-word characters.
  1563. */
  1564. public static function getInputId($model, $attribute)
  1565. {
  1566. $name = strtolower(static::getInputName($model, $attribute));
  1567. return str_replace(['[]', '][', '[', ']', ' '], ['', '-', '-', '', '-'], $name);
  1568. }
  1569. }