BaseHtml.php 107 KB

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