BaseHtml.php 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329
  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 https://secure.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 https://secure.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. // 'checked' option has priority over $checked argument
  697. if (!isset($options['checked'])) {
  698. $options['checked'] = (bool) $checked;
  699. }
  700. $value = array_key_exists('value', $options) ? $options['value'] : '1';
  701. if (isset($options['uncheck'])) {
  702. // add a hidden field so that if the checkbox is not selected, it still submits a value
  703. $hiddenOptions = [];
  704. if (isset($options['form'])) {
  705. $hiddenOptions['form'] = $options['form'];
  706. }
  707. // make sure disabled input is not sending any value
  708. if (!empty($options['disabled'])) {
  709. $hiddenOptions['disabled'] = $options['disabled'];
  710. }
  711. $hidden = static::hiddenInput($name, $options['uncheck'], $hiddenOptions);
  712. unset($options['uncheck']);
  713. } else {
  714. $hidden = '';
  715. }
  716. if (isset($options['label'])) {
  717. $label = $options['label'];
  718. $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
  719. unset($options['label'], $options['labelOptions']);
  720. $content = static::label(static::input($type, $name, $value, $options) . ' ' . $label, null, $labelOptions);
  721. return $hidden . $content;
  722. }
  723. return $hidden . static::input($type, $name, $value, $options);
  724. }
  725. /**
  726. * Generates a drop-down list.
  727. * @param string $name the input name
  728. * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
  729. * @param array $items the option data items. The array keys are option values, and the array values
  730. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  731. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  732. * If you have a list of data models, you may convert them into the format described above using
  733. * [[\yii\helpers\ArrayHelper::map()]].
  734. *
  735. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  736. * the labels will also be HTML-encoded.
  737. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  738. *
  739. * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
  740. * to override the value and to set other tag attributes:
  741. *
  742. * ```php
  743. * ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
  744. * ```
  745. *
  746. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  747. * and the array values are the extra attributes for the corresponding option tags. For example,
  748. *
  749. * ```php
  750. * [
  751. * 'value1' => ['disabled' => true],
  752. * 'value2' => ['label' => 'value 2'],
  753. * ];
  754. * ```
  755. *
  756. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  757. * except that the array keys represent the optgroup labels specified in $items.
  758. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
  759. * Defaults to false.
  760. * - encode: bool, whether to encode option prompt and option value characters.
  761. * Defaults to `true`. This option is available since 2.0.3.
  762. *
  763. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  764. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  765. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  766. *
  767. * @return string the generated drop-down list tag
  768. */
  769. public static function dropDownList($name, $selection = null, $items = [], $options = [])
  770. {
  771. if (!empty($options['multiple'])) {
  772. return static::listBox($name, $selection, $items, $options);
  773. }
  774. $options['name'] = $name;
  775. unset($options['unselect']);
  776. $selectOptions = static::renderSelectOptions($selection, $items, $options);
  777. return static::tag('select', "\n" . $selectOptions . "\n", $options);
  778. }
  779. /**
  780. * Generates a list box.
  781. * @param string $name the input name
  782. * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
  783. * @param array $items the option data items. The array keys are option values, and the array values
  784. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  785. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  786. * If you have a list of data models, you may convert them into the format described above using
  787. * [[\yii\helpers\ArrayHelper::map()]].
  788. *
  789. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  790. * the labels will also be HTML-encoded.
  791. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  792. *
  793. * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
  794. * to override the value and to set other tag attributes:
  795. *
  796. * ```php
  797. * ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
  798. * ```
  799. *
  800. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  801. * and the array values are the extra attributes for the corresponding option tags. For example,
  802. *
  803. * ```php
  804. * [
  805. * 'value1' => ['disabled' => true],
  806. * 'value2' => ['label' => 'value 2'],
  807. * ];
  808. * ```
  809. *
  810. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  811. * except that the array keys represent the optgroup labels specified in $items.
  812. * - unselect: string, the value that will be submitted when no option is selected.
  813. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
  814. * mode, we can still obtain the posted unselect value.
  815. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
  816. * Defaults to false.
  817. * - encode: bool, whether to encode option prompt and option value characters.
  818. * Defaults to `true`. This option is available since 2.0.3.
  819. *
  820. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  821. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  822. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  823. *
  824. * @return string the generated list box tag
  825. */
  826. public static function listBox($name, $selection = null, $items = [], $options = [])
  827. {
  828. if (!array_key_exists('size', $options)) {
  829. $options['size'] = 4;
  830. }
  831. if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) {
  832. $name .= '[]';
  833. }
  834. $options['name'] = $name;
  835. if (isset($options['unselect'])) {
  836. // add a hidden field so that if the list box has no option being selected, it still submits a value
  837. if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) {
  838. $name = substr($name, 0, -2);
  839. }
  840. $hiddenOptions = [];
  841. // make sure disabled input is not sending any value
  842. if (!empty($options['disabled'])) {
  843. $hiddenOptions['disabled'] = $options['disabled'];
  844. }
  845. $hidden = static::hiddenInput($name, $options['unselect'], $hiddenOptions);
  846. unset($options['unselect']);
  847. } else {
  848. $hidden = '';
  849. }
  850. $selectOptions = static::renderSelectOptions($selection, $items, $options);
  851. return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
  852. }
  853. /**
  854. * Generates a list of checkboxes.
  855. * A checkbox list allows multiple selection, like [[listBox()]].
  856. * As a result, the corresponding submitted value is an array.
  857. * @param string $name the name attribute of each checkbox.
  858. * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
  859. * @param array $items the data item used to generate the checkboxes.
  860. * The array keys are the checkbox values, while the array values are the corresponding labels.
  861. * @param array $options options (name => config) for the checkbox list container tag.
  862. * The following options are specially handled:
  863. *
  864. * - tag: string|false, the tag name of the container element. False to render checkbox without container.
  865. * See also [[tag()]].
  866. * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
  867. * By setting this option, a hidden input will be generated.
  868. * - disabled: boolean, whether the generated by unselect option hidden input should be disabled. Defaults to false.
  869. * This option is available since version 2.0.16.
  870. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  871. * This option is ignored if `item` option is set.
  872. * - separator: string, the HTML code that separates items.
  873. * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
  874. * - item: callable, a callback that can be used to customize the generation of the HTML code
  875. * corresponding to a single item in $items. The signature of this callback must be:
  876. *
  877. * ```php
  878. * function ($index, $label, $name, $checked, $value)
  879. * ```
  880. *
  881. * where $index is the zero-based index of the checkbox in the whole list; $label
  882. * is the label for the checkbox; and $name, $value and $checked represent the name,
  883. * value and the checked status of the checkbox input, respectively.
  884. *
  885. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  886. *
  887. * @return string the generated checkbox list
  888. */
  889. public static function checkboxList($name, $selection = null, $items = [], $options = [])
  890. {
  891. if (substr($name, -2) !== '[]') {
  892. $name .= '[]';
  893. }
  894. if (ArrayHelper::isTraversable($selection)) {
  895. $selection = array_map('strval', (array)$selection);
  896. }
  897. $formatter = ArrayHelper::remove($options, 'item');
  898. $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
  899. $encode = ArrayHelper::remove($options, 'encode', true);
  900. $separator = ArrayHelper::remove($options, 'separator', "\n");
  901. $tag = ArrayHelper::remove($options, 'tag', 'div');
  902. $lines = [];
  903. $index = 0;
  904. foreach ($items as $value => $label) {
  905. $checked = $selection !== null &&
  906. (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
  907. || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, $selection));
  908. if ($formatter !== null) {
  909. $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
  910. } else {
  911. $lines[] = static::checkbox($name, $checked, array_merge([
  912. 'value' => $value,
  913. 'label' => $encode ? static::encode($label) : $label,
  914. ], $itemOptions));
  915. }
  916. $index++;
  917. }
  918. if (isset($options['unselect'])) {
  919. // add a hidden field so that if the list box has no option being selected, it still submits a value
  920. $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
  921. $hiddenOptions = [];
  922. // make sure disabled input is not sending any value
  923. if (!empty($options['disabled'])) {
  924. $hiddenOptions['disabled'] = $options['disabled'];
  925. }
  926. $hidden = static::hiddenInput($name2, $options['unselect'], $hiddenOptions);
  927. unset($options['unselect'], $options['disabled']);
  928. } else {
  929. $hidden = '';
  930. }
  931. $visibleContent = implode($separator, $lines);
  932. if ($tag === false) {
  933. return $hidden . $visibleContent;
  934. }
  935. return $hidden . static::tag($tag, $visibleContent, $options);
  936. }
  937. /**
  938. * Generates a list of radio buttons.
  939. * A radio button list is like a checkbox list, except that it only allows single selection.
  940. * @param string $name the name attribute of each radio button.
  941. * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
  942. * @param array $items the data item used to generate the radio buttons.
  943. * The array keys are the radio button values, while the array values are the corresponding labels.
  944. * @param array $options options (name => config) for the radio button list container tag.
  945. * The following options are specially handled:
  946. *
  947. * - tag: string|false, the tag name of the container element. False to render radio buttons without container.
  948. * See also [[tag()]].
  949. * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
  950. * By setting this option, a hidden input will be generated.
  951. * - disabled: boolean, whether the generated by unselect option hidden input should be disabled. Defaults to false.
  952. * This option is available since version 2.0.16.
  953. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  954. * This option is ignored if `item` option is set.
  955. * - separator: string, the HTML code that separates items.
  956. * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
  957. * - item: callable, a callback that can be used to customize the generation of the HTML code
  958. * corresponding to a single item in $items. The signature of this callback must be:
  959. *
  960. * ```php
  961. * function ($index, $label, $name, $checked, $value)
  962. * ```
  963. *
  964. * where $index is the zero-based index of the radio button in the whole list; $label
  965. * is the label for the radio button; and $name, $value and $checked represent the name,
  966. * value and the checked status of the radio button input, respectively.
  967. *
  968. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  969. *
  970. * @return string the generated radio button list
  971. */
  972. public static function radioList($name, $selection = null, $items = [], $options = [])
  973. {
  974. if (ArrayHelper::isTraversable($selection)) {
  975. $selection = array_map('strval', (array)$selection);
  976. }
  977. $formatter = ArrayHelper::remove($options, 'item');
  978. $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
  979. $encode = ArrayHelper::remove($options, 'encode', true);
  980. $separator = ArrayHelper::remove($options, 'separator', "\n");
  981. $tag = ArrayHelper::remove($options, 'tag', 'div');
  982. $hidden = '';
  983. if (isset($options['unselect'])) {
  984. // add a hidden field so that if the list box has no option being selected, it still submits a value
  985. $hiddenOptions = [];
  986. // make sure disabled input is not sending any value
  987. if (!empty($options['disabled'])) {
  988. $hiddenOptions['disabled'] = $options['disabled'];
  989. }
  990. $hidden = static::hiddenInput($name, $options['unselect'], $hiddenOptions);
  991. unset($options['unselect'], $options['disabled']);
  992. }
  993. $lines = [];
  994. $index = 0;
  995. foreach ($items as $value => $label) {
  996. $checked = $selection !== null &&
  997. (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
  998. || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, $selection));
  999. if ($formatter !== null) {
  1000. $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
  1001. } else {
  1002. $lines[] = static::radio($name, $checked, array_merge([
  1003. 'value' => $value,
  1004. 'label' => $encode ? static::encode($label) : $label,
  1005. ], $itemOptions));
  1006. }
  1007. $index++;
  1008. }
  1009. $visibleContent = implode($separator, $lines);
  1010. if ($tag === false) {
  1011. return $hidden . $visibleContent;
  1012. }
  1013. return $hidden . static::tag($tag, $visibleContent, $options);
  1014. }
  1015. /**
  1016. * Generates an unordered list.
  1017. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
  1018. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
  1019. * @param array $options options (name => config) for the radio button list. The following options are supported:
  1020. *
  1021. * - encode: boolean, whether to HTML-encode the items. Defaults to true.
  1022. * This option is ignored if the `item` option is specified.
  1023. * - separator: string, the HTML code that separates items. Defaults to a simple newline (`"\n"`).
  1024. * This option is available since version 2.0.7.
  1025. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
  1026. * - item: callable, a callback that is used to generate each individual list item.
  1027. * The signature of this callback must be:
  1028. *
  1029. * ```php
  1030. * function ($item, $index)
  1031. * ```
  1032. *
  1033. * where $index is the array key corresponding to `$item` in `$items`. The callback should return
  1034. * the whole list item tag.
  1035. *
  1036. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1037. *
  1038. * @return string the generated unordered list. An empty list tag will be returned if `$items` is empty.
  1039. */
  1040. public static function ul($items, $options = [])
  1041. {
  1042. $tag = ArrayHelper::remove($options, 'tag', 'ul');
  1043. $encode = ArrayHelper::remove($options, 'encode', true);
  1044. $formatter = ArrayHelper::remove($options, 'item');
  1045. $separator = ArrayHelper::remove($options, 'separator', "\n");
  1046. $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
  1047. if (empty($items)) {
  1048. return static::tag($tag, '', $options);
  1049. }
  1050. $results = [];
  1051. foreach ($items as $index => $item) {
  1052. if ($formatter !== null) {
  1053. $results[] = call_user_func($formatter, $item, $index);
  1054. } else {
  1055. $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
  1056. }
  1057. }
  1058. return static::tag(
  1059. $tag,
  1060. $separator . implode($separator, $results) . $separator,
  1061. $options
  1062. );
  1063. }
  1064. /**
  1065. * Generates an ordered list.
  1066. * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
  1067. * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
  1068. * @param array $options options (name => config) for the radio button list. The following options are supported:
  1069. *
  1070. * - encode: boolean, whether to HTML-encode the items. Defaults to true.
  1071. * This option is ignored if the `item` option is specified.
  1072. * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
  1073. * - item: callable, a callback that is used to generate each individual list item.
  1074. * The signature of this callback must be:
  1075. *
  1076. * ```php
  1077. * function ($item, $index)
  1078. * ```
  1079. *
  1080. * where $index is the array key corresponding to `$item` in `$items`. The callback should return
  1081. * the whole list item tag.
  1082. *
  1083. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1084. *
  1085. * @return string the generated ordered list. An empty string is returned if `$items` is empty.
  1086. */
  1087. public static function ol($items, $options = [])
  1088. {
  1089. $options['tag'] = 'ol';
  1090. return static::ul($items, $options);
  1091. }
  1092. /**
  1093. * Generates a label tag for the given model attribute.
  1094. * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
  1095. * @param Model $model the model object
  1096. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1097. * about attribute expression.
  1098. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1099. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1100. * If a value is null, the corresponding attribute will not be rendered.
  1101. * The following options are specially handled:
  1102. *
  1103. * - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
  1104. * If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
  1105. * (after encoding).
  1106. *
  1107. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1108. *
  1109. * @return string the generated label tag
  1110. */
  1111. public static function activeLabel($model, $attribute, $options = [])
  1112. {
  1113. $for = ArrayHelper::remove($options, 'for', static::getInputId($model, $attribute));
  1114. $attribute = static::getAttributeName($attribute);
  1115. $label = ArrayHelper::remove($options, 'label', static::encode($model->getAttributeLabel($attribute)));
  1116. return static::label($label, $for, $options);
  1117. }
  1118. /**
  1119. * Generates a hint tag for the given model attribute.
  1120. * The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]].
  1121. * If no hint content can be obtained, method will return an empty string.
  1122. * @param Model $model the model object
  1123. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1124. * about attribute expression.
  1125. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1126. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1127. * If a value is null, the corresponding attribute will not be rendered.
  1128. * The following options are specially handled:
  1129. *
  1130. * - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]].
  1131. * If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display
  1132. * (without encoding).
  1133. *
  1134. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1135. *
  1136. * @return string the generated hint tag
  1137. * @since 2.0.4
  1138. */
  1139. public static function activeHint($model, $attribute, $options = [])
  1140. {
  1141. $attribute = static::getAttributeName($attribute);
  1142. $hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute);
  1143. if (empty($hint)) {
  1144. return '';
  1145. }
  1146. $tag = ArrayHelper::remove($options, 'tag', 'div');
  1147. unset($options['hint']);
  1148. return static::tag($tag, $hint, $options);
  1149. }
  1150. /**
  1151. * Generates a summary of the validation errors.
  1152. * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
  1153. * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
  1154. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1155. *
  1156. * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
  1157. * - footer: string, the footer HTML for the error summary. Defaults to empty string.
  1158. * - encode: boolean, if set to false then the error messages won't be encoded. Defaults to `true`.
  1159. * - 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. Defaults to `false`.
  1161. * Option is available since 2.0.10.
  1162. *
  1163. * The rest of the options will be rendered as the attributes of the container tag.
  1164. *
  1165. * @return string the generated error summary
  1166. */
  1167. public static function errorSummary($models, $options = [])
  1168. {
  1169. $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
  1170. $footer = ArrayHelper::remove($options, 'footer', '');
  1171. $encode = ArrayHelper::remove($options, 'encode', true);
  1172. $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
  1173. unset($options['header']);
  1174. $lines = self::collectErrors($models, $encode, $showAllErrors);
  1175. if (empty($lines)) {
  1176. // still render the placeholder for client-side validation use
  1177. $content = '<ul></ul>';
  1178. $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
  1179. } else {
  1180. $content = '<ul><li>' . implode("</li>\n<li>", $lines) . '</li></ul>';
  1181. }
  1182. return Html::tag('div', $header . $content . $footer, $options);
  1183. }
  1184. /**
  1185. * Return array of the validation errors
  1186. * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
  1187. * @param $encode boolean, if set to false then the error messages won't be encoded.
  1188. * @param $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
  1189. * only the first error message for each attribute will be shown.
  1190. * @return array of the validation errors
  1191. * @since 2.0.14
  1192. */
  1193. private static function collectErrors($models, $encode, $showAllErrors)
  1194. {
  1195. $lines = [];
  1196. if (!is_array($models)) {
  1197. $models = [$models];
  1198. }
  1199. foreach ($models as $model) {
  1200. $lines = array_unique(array_merge($lines, $model->getErrorSummary($showAllErrors)));
  1201. }
  1202. // If there are the same error messages for different attributes, array_unique will leave gaps
  1203. // between sequential keys. Applying array_values to reorder array keys.
  1204. $lines = array_values($lines);
  1205. if ($encode) {
  1206. foreach ($lines as &$line) {
  1207. $line = Html::encode($line);
  1208. }
  1209. }
  1210. return $lines;
  1211. }
  1212. /**
  1213. * Generates a tag that contains the first validation error of the specified model attribute.
  1214. * Note that even if there is no validation error, this method will still return an empty error tag.
  1215. * @param Model $model the model object
  1216. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1217. * about attribute expression.
  1218. * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
  1219. * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1220. *
  1221. * The following options are specially handled:
  1222. *
  1223. * - tag: this specifies the tag name. If not set, "div" will be used.
  1224. * See also [[tag()]].
  1225. * - encode: boolean, if set to false then the error message won't be encoded.
  1226. * - errorSource (since 2.0.14): \Closure|callable, callback that will be called to obtain an error message.
  1227. * The signature of the callback must be: `function ($model, $attribute)` and return a string.
  1228. * When not set, the `$model->getFirstError()` method will be called.
  1229. *
  1230. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1231. *
  1232. * @return string the generated label tag
  1233. */
  1234. public static function error($model, $attribute, $options = [])
  1235. {
  1236. $attribute = static::getAttributeName($attribute);
  1237. $errorSource = ArrayHelper::remove($options, 'errorSource');
  1238. if ($errorSource !== null) {
  1239. $error = call_user_func($errorSource, $model, $attribute);
  1240. } else {
  1241. $error = $model->getFirstError($attribute);
  1242. }
  1243. $tag = ArrayHelper::remove($options, 'tag', 'div');
  1244. $encode = ArrayHelper::remove($options, 'encode', true);
  1245. return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
  1246. }
  1247. /**
  1248. * Generates an input tag for the given model attribute.
  1249. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1250. * unless they are explicitly specified in `$options`.
  1251. * @param string $type the input type (e.g. 'text', 'password')
  1252. * @param Model $model the model object
  1253. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1254. * about attribute expression.
  1255. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1256. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1257. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1258. * @return string the generated input tag
  1259. */
  1260. public static function activeInput($type, $model, $attribute, $options = [])
  1261. {
  1262. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1263. $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
  1264. if (!array_key_exists('id', $options)) {
  1265. $options['id'] = static::getInputId($model, $attribute);
  1266. }
  1267. static::setActivePlaceholder($model, $attribute, $options);
  1268. self::normalizeMaxLength($model, $attribute, $options);
  1269. return static::input($type, $name, $value, $options);
  1270. }
  1271. /**
  1272. * If `maxlength` option is set true and the model attribute is validated by a string validator,
  1273. * the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  1274. * @param Model $model the model object
  1275. * @param string $attribute the attribute name or expression.
  1276. * @param array $options the tag options in terms of name-value pairs.
  1277. */
  1278. private static function normalizeMaxLength($model, $attribute, &$options)
  1279. {
  1280. if (isset($options['maxlength']) && $options['maxlength'] === true) {
  1281. unset($options['maxlength']);
  1282. $attrName = static::getAttributeName($attribute);
  1283. foreach ($model->getActiveValidators($attrName) as $validator) {
  1284. if ($validator instanceof StringValidator && $validator->max !== null) {
  1285. $options['maxlength'] = $validator->max;
  1286. break;
  1287. }
  1288. }
  1289. }
  1290. }
  1291. /**
  1292. * Generates a text input tag for the given model attribute.
  1293. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1294. * unless they are explicitly specified in `$options`.
  1295. * @param Model $model the model object
  1296. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1297. * about attribute expression.
  1298. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1299. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1300. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1301. * The following special options are recognized:
  1302. *
  1303. * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
  1304. * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  1305. * This is available since version 2.0.3.
  1306. * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
  1307. * as a placeholder (this behavior is available since version 2.0.14).
  1308. *
  1309. * @return string the generated input tag
  1310. */
  1311. public static function activeTextInput($model, $attribute, $options = [])
  1312. {
  1313. return static::activeInput('text', $model, $attribute, $options);
  1314. }
  1315. /**
  1316. * Generate placeholder from model attribute label.
  1317. *
  1318. * @param Model $model the model object
  1319. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1320. * about attribute expression.
  1321. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1322. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1323. * @since 2.0.14
  1324. */
  1325. protected static function setActivePlaceholder($model, $attribute, &$options = [])
  1326. {
  1327. if (isset($options['placeholder']) && $options['placeholder'] === true) {
  1328. $attribute = static::getAttributeName($attribute);
  1329. $options['placeholder'] = $model->getAttributeLabel($attribute);
  1330. }
  1331. }
  1332. /**
  1333. * Generates a hidden input tag for the given model attribute.
  1334. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1335. * unless they are explicitly specified in `$options`.
  1336. * @param Model $model the model object
  1337. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1338. * about attribute expression.
  1339. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1340. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1341. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1342. * @return string the generated input tag
  1343. */
  1344. public static function activeHiddenInput($model, $attribute, $options = [])
  1345. {
  1346. return static::activeInput('hidden', $model, $attribute, $options);
  1347. }
  1348. /**
  1349. * Generates a password input tag for the given model attribute.
  1350. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1351. * unless they are explicitly specified in `$options`.
  1352. * @param Model $model the model object
  1353. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1354. * about attribute expression.
  1355. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1356. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1357. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1358. * The following special options are recognized:
  1359. *
  1360. * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
  1361. * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  1362. * This option is available since version 2.0.6.
  1363. * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
  1364. * as a placeholder (this behavior is available since version 2.0.14).
  1365. *
  1366. * @return string the generated input tag
  1367. */
  1368. public static function activePasswordInput($model, $attribute, $options = [])
  1369. {
  1370. return static::activeInput('password', $model, $attribute, $options);
  1371. }
  1372. /**
  1373. * Generates a file input tag for the given model attribute.
  1374. * This method will generate the "name" and "value" tag attributes automatically for the model attribute
  1375. * unless they are explicitly specified in `$options`.
  1376. * Additionally, if a separate set of HTML options array is defined inside `$options` with a key named `hiddenOptions`,
  1377. * it will be passed to the `activeHiddenInput` field as its own `$options` parameter.
  1378. * @param Model $model the model object
  1379. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1380. * about attribute expression.
  1381. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1382. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1383. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1384. * If `hiddenOptions` parameter which is another set of HTML options array is defined, it will be extracted
  1385. * from `$options` to be used for the hidden input.
  1386. * @return string the generated input tag
  1387. */
  1388. public static function activeFileInput($model, $attribute, $options = [])
  1389. {
  1390. $hiddenOptions = ['id' => null, 'value' => ''];
  1391. if (isset($options['name'])) {
  1392. $hiddenOptions['name'] = $options['name'];
  1393. }
  1394. // make sure disabled input is not sending any value
  1395. if (!empty($options['disabled'])) {
  1396. $hiddenOptions['disabled'] = $options['disabled'];
  1397. }
  1398. $hiddenOptions = ArrayHelper::merge($hiddenOptions, ArrayHelper::remove($options, 'hiddenOptions', []));
  1399. // Add a hidden field so that if a model only has a file field, we can
  1400. // still use isset($_POST[$modelClass]) to detect if the input is submitted.
  1401. // The hidden input will be assigned its own set of html options via `$hiddenOptions`.
  1402. // This provides the possibility to interact with the hidden field via client script.
  1403. // Note: For file-field-only model with `disabled` option set to `true` input submitting detection won't work.
  1404. return static::activeHiddenInput($model, $attribute, $hiddenOptions)
  1405. . static::activeInput('file', $model, $attribute, $options);
  1406. }
  1407. /**
  1408. * Generates a textarea tag for the given model attribute.
  1409. * The model attribute value will be used as the content in the textarea.
  1410. * @param Model $model the model object
  1411. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1412. * about attribute expression.
  1413. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  1414. * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
  1415. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1416. * The following special options are recognized:
  1417. *
  1418. * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
  1419. * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  1420. * This option is available since version 2.0.6.
  1421. * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
  1422. * as a placeholder (this behavior is available since version 2.0.14).
  1423. *
  1424. * @return string the generated textarea tag
  1425. */
  1426. public static function activeTextarea($model, $attribute, $options = [])
  1427. {
  1428. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1429. if (isset($options['value'])) {
  1430. $value = $options['value'];
  1431. unset($options['value']);
  1432. } else {
  1433. $value = static::getAttributeValue($model, $attribute);
  1434. }
  1435. if (!array_key_exists('id', $options)) {
  1436. $options['id'] = static::getInputId($model, $attribute);
  1437. }
  1438. self::normalizeMaxLength($model, $attribute, $options);
  1439. static::setActivePlaceholder($model, $attribute, $options);
  1440. return static::textarea($name, $value, $options);
  1441. }
  1442. /**
  1443. * Generates a radio button tag together with a label for the given model attribute.
  1444. * This method will generate the "checked" tag attribute according to the model attribute value.
  1445. * @param Model $model the model object
  1446. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1447. * about attribute expression.
  1448. * @param array $options the tag options in terms of name-value pairs.
  1449. * See [[booleanInput()]] for details about accepted attributes.
  1450. *
  1451. * @return string the generated radio button tag
  1452. */
  1453. public static function activeRadio($model, $attribute, $options = [])
  1454. {
  1455. return static::activeBooleanInput('radio', $model, $attribute, $options);
  1456. }
  1457. /**
  1458. * Generates a checkbox tag together with a label for the given model attribute.
  1459. * This method will generate the "checked" tag attribute according to the model attribute value.
  1460. * @param Model $model the model object
  1461. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1462. * about attribute expression.
  1463. * @param array $options the tag options in terms of name-value pairs.
  1464. * See [[booleanInput()]] for details about accepted attributes.
  1465. *
  1466. * @return string the generated checkbox tag
  1467. */
  1468. public static function activeCheckbox($model, $attribute, $options = [])
  1469. {
  1470. return static::activeBooleanInput('checkbox', $model, $attribute, $options);
  1471. }
  1472. /**
  1473. * Generates a boolean input
  1474. * This method is mainly called by [[activeCheckbox()]] and [[activeRadio()]].
  1475. * @param string $type the input type. This can be either `radio` or `checkbox`.
  1476. * @param Model $model the model object
  1477. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1478. * about attribute expression.
  1479. * @param array $options the tag options in terms of name-value pairs.
  1480. * See [[booleanInput()]] for details about accepted attributes.
  1481. * @return string the generated input element
  1482. * @since 2.0.9
  1483. */
  1484. protected static function activeBooleanInput($type, $model, $attribute, $options = [])
  1485. {
  1486. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1487. $value = static::getAttributeValue($model, $attribute);
  1488. if (!array_key_exists('value', $options)) {
  1489. $options['value'] = '1';
  1490. }
  1491. if (!array_key_exists('uncheck', $options)) {
  1492. $options['uncheck'] = '0';
  1493. } elseif ($options['uncheck'] === false) {
  1494. unset($options['uncheck']);
  1495. }
  1496. if (!array_key_exists('label', $options)) {
  1497. $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
  1498. } elseif ($options['label'] === false) {
  1499. unset($options['label']);
  1500. }
  1501. $checked = "$value" === "{$options['value']}";
  1502. if (!array_key_exists('id', $options)) {
  1503. $options['id'] = static::getInputId($model, $attribute);
  1504. }
  1505. return static::$type($name, $checked, $options);
  1506. }
  1507. /**
  1508. * Generates a drop-down list for the given model attribute.
  1509. * The selection of the drop-down list is taken from the value of the model attribute.
  1510. * @param Model $model the model object
  1511. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1512. * about attribute expression.
  1513. * @param array $items the option data items. The array keys are option values, and the array values
  1514. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  1515. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  1516. * If you have a list of data models, you may convert them into the format described above using
  1517. * [[\yii\helpers\ArrayHelper::map()]].
  1518. *
  1519. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  1520. * the labels will also be HTML-encoded.
  1521. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1522. *
  1523. * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
  1524. * to override the value and to set other tag attributes:
  1525. *
  1526. * ```php
  1527. * ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
  1528. * ```
  1529. *
  1530. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  1531. * and the array values are the extra attributes for the corresponding option tags. For example,
  1532. *
  1533. * ```php
  1534. * [
  1535. * 'value1' => ['disabled' => true],
  1536. * 'value2' => ['label' => 'value 2'],
  1537. * ];
  1538. * ```
  1539. *
  1540. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  1541. * except that the array keys represent the optgroup labels specified in $items.
  1542. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
  1543. * Defaults to false.
  1544. * - encode: bool, whether to encode option prompt and option value characters.
  1545. * Defaults to `true`. This option is available since 2.0.3.
  1546. *
  1547. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  1548. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1549. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1550. *
  1551. * @return string the generated drop-down list tag
  1552. */
  1553. public static function activeDropDownList($model, $attribute, $items, $options = [])
  1554. {
  1555. if (empty($options['multiple'])) {
  1556. return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
  1557. }
  1558. return static::activeListBox($model, $attribute, $items, $options);
  1559. }
  1560. /**
  1561. * Generates a list box.
  1562. * The selection of the list box is taken from the value of the model attribute.
  1563. * @param Model $model the model object
  1564. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1565. * about attribute expression.
  1566. * @param array $items the option data items. The array keys are option values, and the array values
  1567. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  1568. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  1569. * If you have a list of data models, you may convert them into the format described above using
  1570. * [[\yii\helpers\ArrayHelper::map()]].
  1571. *
  1572. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  1573. * the labels will also be HTML-encoded.
  1574. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  1575. *
  1576. * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
  1577. * to override the value and to set other tag attributes:
  1578. *
  1579. * ```php
  1580. * ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
  1581. * ```
  1582. *
  1583. * - options: array, the attributes for the select option tags. The array keys must be valid option values,
  1584. * and the array values are the extra attributes for the corresponding option tags. For example,
  1585. *
  1586. * ```php
  1587. * [
  1588. * 'value1' => ['disabled' => true],
  1589. * 'value2' => ['label' => 'value 2'],
  1590. * ];
  1591. * ```
  1592. *
  1593. * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
  1594. * except that the array keys represent the optgroup labels specified in $items.
  1595. * - unselect: string, the value that will be submitted when no option is selected.
  1596. * When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
  1597. * mode, we can still obtain the posted unselect value.
  1598. * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
  1599. * Defaults to false.
  1600. * - encode: bool, whether to encode option prompt and option value characters.
  1601. * Defaults to `true`. This option is available since 2.0.3.
  1602. *
  1603. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  1604. * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
  1605. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1606. *
  1607. * @return string the generated list box tag
  1608. */
  1609. public static function activeListBox($model, $attribute, $items, $options = [])
  1610. {
  1611. return static::activeListInput('listBox', $model, $attribute, $items, $options);
  1612. }
  1613. /**
  1614. * Generates a list of checkboxes.
  1615. * A checkbox list allows multiple selection, like [[listBox()]].
  1616. * As a result, the corresponding submitted value is an array.
  1617. * The selection of the checkbox list is taken from the value of the model attribute.
  1618. * @param Model $model the model object
  1619. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1620. * about attribute expression.
  1621. * @param array $items the data item used to generate the checkboxes.
  1622. * The array keys are the checkbox values, and the array values are the corresponding labels.
  1623. * Note that the labels will NOT be HTML-encoded, while the values will.
  1624. * @param array $options options (name => config) for the checkbox list container tag.
  1625. * The following options are specially handled:
  1626. *
  1627. * - tag: string|false, the tag name of the container element. False to render checkbox without container.
  1628. * See also [[tag()]].
  1629. * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
  1630. * You may set this option to be null to prevent default value submission.
  1631. * If this option is not set, an empty string will be submitted.
  1632. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  1633. * This option is ignored if `item` option is set.
  1634. * - separator: string, the HTML code that separates items.
  1635. * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
  1636. * - item: callable, a callback that can be used to customize the generation of the HTML code
  1637. * corresponding to a single item in $items. The signature of this callback must be:
  1638. *
  1639. * ```php
  1640. * function ($index, $label, $name, $checked, $value)
  1641. * ```
  1642. *
  1643. * where $index is the zero-based index of the checkbox in the whole list; $label
  1644. * is the label for the checkbox; and $name, $value and $checked represent the name,
  1645. * value and the checked status of the checkbox input.
  1646. *
  1647. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1648. *
  1649. * @return string the generated checkbox list
  1650. */
  1651. public static function activeCheckboxList($model, $attribute, $items, $options = [])
  1652. {
  1653. return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
  1654. }
  1655. /**
  1656. * Generates a list of radio buttons.
  1657. * A radio button list is like a checkbox list, except that it only allows single selection.
  1658. * The selection of the radio buttons is taken from the value of the model attribute.
  1659. * @param Model $model the model object
  1660. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1661. * about attribute expression.
  1662. * @param array $items the data item used to generate the radio buttons.
  1663. * The array keys are the radio values, and the array values are the corresponding labels.
  1664. * Note that the labels will NOT be HTML-encoded, while the values will.
  1665. * @param array $options options (name => config) for the radio button list container tag.
  1666. * The following options are specially handled:
  1667. *
  1668. * - tag: string|false, the tag name of the container element. False to render radio button without container.
  1669. * See also [[tag()]].
  1670. * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
  1671. * You may set this option to be null to prevent default value submission.
  1672. * If this option is not set, an empty string will be submitted.
  1673. * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
  1674. * This option is ignored if `item` option is set.
  1675. * - separator: string, the HTML code that separates items.
  1676. * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
  1677. * - item: callable, a callback that can be used to customize the generation of the HTML code
  1678. * corresponding to a single item in $items. The signature of this callback must be:
  1679. *
  1680. * ```php
  1681. * function ($index, $label, $name, $checked, $value)
  1682. * ```
  1683. *
  1684. * where $index is the zero-based index of the radio button in the whole list; $label
  1685. * is the label for the radio button; and $name, $value and $checked represent the name,
  1686. * value and the checked status of the radio button input.
  1687. *
  1688. * See [[renderTagAttributes()]] for details on how attributes are being rendered.
  1689. *
  1690. * @return string the generated radio button list
  1691. */
  1692. public static function activeRadioList($model, $attribute, $items, $options = [])
  1693. {
  1694. return static::activeListInput('radioList', $model, $attribute, $items, $options);
  1695. }
  1696. /**
  1697. * Generates a list of input fields.
  1698. * This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckboxList()]].
  1699. * @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'.
  1700. * @param Model $model the model object
  1701. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
  1702. * about attribute expression.
  1703. * @param array $items the data item used to generate the input fields.
  1704. * The array keys are the input values, and the array values are the corresponding labels.
  1705. * Note that the labels will NOT be HTML-encoded, while the values will.
  1706. * @param array $options options (name => config) for the input list. The supported special options
  1707. * depend on the input type specified by `$type`.
  1708. * @return string the generated input list
  1709. */
  1710. protected static function activeListInput($type, $model, $attribute, $items, $options = [])
  1711. {
  1712. $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
  1713. $selection = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
  1714. if (!array_key_exists('unselect', $options)) {
  1715. $options['unselect'] = '';
  1716. }
  1717. if (!array_key_exists('id', $options)) {
  1718. $options['id'] = static::getInputId($model, $attribute);
  1719. }
  1720. return static::$type($name, $selection, $items, $options);
  1721. }
  1722. /**
  1723. * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
  1724. * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
  1725. * @param array $items the option data items. The array keys are option values, and the array values
  1726. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  1727. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  1728. * If you have a list of data models, you may convert them into the format described above using
  1729. * [[\yii\helpers\ArrayHelper::map()]].
  1730. *
  1731. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  1732. * the labels will also be HTML-encoded.
  1733. * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
  1734. * This method will take out these elements, if any: "prompt", "options" and "groups". See more details
  1735. * in [[dropDownList()]] for the explanation of these elements.
  1736. *
  1737. * @return string the generated list options
  1738. */
  1739. public static function renderSelectOptions($selection, $items, &$tagOptions = [])
  1740. {
  1741. if (ArrayHelper::isTraversable($selection)) {
  1742. $selection = array_map('strval', (array)$selection);
  1743. }
  1744. $lines = [];
  1745. $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
  1746. $encode = ArrayHelper::remove($tagOptions, 'encode', true);
  1747. if (isset($tagOptions['prompt'])) {
  1748. $promptOptions = ['value' => ''];
  1749. if (is_string($tagOptions['prompt'])) {
  1750. $promptText = $tagOptions['prompt'];
  1751. } else {
  1752. $promptText = $tagOptions['prompt']['text'];
  1753. $promptOptions = array_merge($promptOptions, $tagOptions['prompt']['options']);
  1754. }
  1755. $promptText = $encode ? static::encode($promptText) : $promptText;
  1756. if ($encodeSpaces) {
  1757. $promptText = str_replace(' ', '&nbsp;', $promptText);
  1758. }
  1759. $lines[] = static::tag('option', $promptText, $promptOptions);
  1760. }
  1761. $options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
  1762. $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
  1763. unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
  1764. $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
  1765. $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
  1766. foreach ($items as $key => $value) {
  1767. if (is_array($value)) {
  1768. $groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
  1769. if (!isset($groupAttrs['label'])) {
  1770. $groupAttrs['label'] = $key;
  1771. }
  1772. $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
  1773. $content = static::renderSelectOptions($selection, $value, $attrs);
  1774. $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
  1775. } else {
  1776. $attrs = isset($options[$key]) ? $options[$key] : [];
  1777. $attrs['value'] = (string) $key;
  1778. if (!array_key_exists('selected', $attrs)) {
  1779. $attrs['selected'] = $selection !== null &&
  1780. (!ArrayHelper::isTraversable($selection) && !strcmp($key, $selection)
  1781. || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$key, $selection));
  1782. }
  1783. $text = $encode ? static::encode($value) : $value;
  1784. if ($encodeSpaces) {
  1785. $text = str_replace(' ', '&nbsp;', $text);
  1786. }
  1787. $lines[] = static::tag('option', $text, $attrs);
  1788. }
  1789. }
  1790. return implode("\n", $lines);
  1791. }
  1792. /**
  1793. * Renders the HTML tag attributes.
  1794. *
  1795. * Attributes whose values are of boolean type will be treated as
  1796. * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
  1797. *
  1798. * Attributes whose values are null will not be rendered.
  1799. *
  1800. * The values of attributes will be HTML-encoded using [[encode()]].
  1801. *
  1802. * The "data" attribute is specially handled when it is receiving an array value. In this case,
  1803. * the array will be "expanded" and a list data attributes will be rendered. For example,
  1804. * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered:
  1805. * `data-id="1" data-name="yii"`.
  1806. * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as:
  1807. * `data-params='{"id":1,"name":"yii"}' data-status="ok"`.
  1808. *
  1809. * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
  1810. * @return string the rendering result. If the attributes are not empty, they will be rendered
  1811. * into a string with a leading white space (so that it can be directly appended to the tag name
  1812. * in a tag. If there is no attribute, an empty string will be returned.
  1813. * @see addCssClass()
  1814. */
  1815. public static function renderTagAttributes($attributes)
  1816. {
  1817. if (count($attributes) > 1) {
  1818. $sorted = [];
  1819. foreach (static::$attributeOrder as $name) {
  1820. if (isset($attributes[$name])) {
  1821. $sorted[$name] = $attributes[$name];
  1822. }
  1823. }
  1824. $attributes = array_merge($sorted, $attributes);
  1825. }
  1826. $html = '';
  1827. foreach ($attributes as $name => $value) {
  1828. if (is_bool($value)) {
  1829. if ($value) {
  1830. $html .= " $name";
  1831. }
  1832. } elseif (is_array($value)) {
  1833. if (in_array($name, static::$dataAttributes)) {
  1834. foreach ($value as $n => $v) {
  1835. if (is_array($v)) {
  1836. $html .= " $name-$n='" . Json::htmlEncode($v) . "'";
  1837. } else {
  1838. $html .= " $name-$n=\"" . static::encode($v) . '"';
  1839. }
  1840. }
  1841. } elseif ($name === 'class') {
  1842. if (empty($value)) {
  1843. continue;
  1844. }
  1845. $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
  1846. } elseif ($name === 'style') {
  1847. if (empty($value)) {
  1848. continue;
  1849. }
  1850. $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
  1851. } else {
  1852. $html .= " $name='" . Json::htmlEncode($value) . "'";
  1853. }
  1854. } elseif ($value !== null) {
  1855. $html .= " $name=\"" . static::encode($value) . '"';
  1856. }
  1857. }
  1858. return $html;
  1859. }
  1860. /**
  1861. * Adds a CSS class (or several classes) to the specified options.
  1862. *
  1863. * If the CSS class is already in the options, it will not be added again.
  1864. * If class specification at given options is an array, and some class placed there with the named (string) key,
  1865. * overriding of such key will have no effect. For example:
  1866. *
  1867. * ```php
  1868. * $options = ['class' => ['persistent' => 'initial']];
  1869. * Html::addCssClass($options, ['persistent' => 'override']);
  1870. * var_dump($options['class']); // outputs: array('persistent' => 'initial');
  1871. * ```
  1872. *
  1873. * @param array $options the options to be modified.
  1874. * @param string|array $class the CSS class(es) to be added
  1875. * @see mergeCssClasses()
  1876. * @see removeCssClass()
  1877. */
  1878. public static function addCssClass(&$options, $class)
  1879. {
  1880. if (isset($options['class'])) {
  1881. if (is_array($options['class'])) {
  1882. $options['class'] = self::mergeCssClasses($options['class'], (array) $class);
  1883. } else {
  1884. $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
  1885. $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
  1886. }
  1887. } else {
  1888. $options['class'] = $class;
  1889. }
  1890. }
  1891. /**
  1892. * Merges already existing CSS classes with new one.
  1893. * This method provides the priority for named existing classes over additional.
  1894. * @param array $existingClasses already existing CSS classes.
  1895. * @param array $additionalClasses CSS classes to be added.
  1896. * @return array merge result.
  1897. * @see addCssClass()
  1898. */
  1899. private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
  1900. {
  1901. foreach ($additionalClasses as $key => $class) {
  1902. if (is_int($key) && !in_array($class, $existingClasses)) {
  1903. $existingClasses[] = $class;
  1904. } elseif (!isset($existingClasses[$key])) {
  1905. $existingClasses[$key] = $class;
  1906. }
  1907. }
  1908. return array_unique($existingClasses);
  1909. }
  1910. /**
  1911. * Removes a CSS class from the specified options.
  1912. * @param array $options the options to be modified.
  1913. * @param string|array $class the CSS class(es) to be removed
  1914. * @see addCssClass()
  1915. */
  1916. public static function removeCssClass(&$options, $class)
  1917. {
  1918. if (isset($options['class'])) {
  1919. if (is_array($options['class'])) {
  1920. $classes = array_diff($options['class'], (array) $class);
  1921. if (empty($classes)) {
  1922. unset($options['class']);
  1923. } else {
  1924. $options['class'] = $classes;
  1925. }
  1926. } else {
  1927. $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
  1928. $classes = array_diff($classes, (array) $class);
  1929. if (empty($classes)) {
  1930. unset($options['class']);
  1931. } else {
  1932. $options['class'] = implode(' ', $classes);
  1933. }
  1934. }
  1935. }
  1936. }
  1937. /**
  1938. * Adds the specified CSS style to the HTML options.
  1939. *
  1940. * If the options already contain a `style` element, the new style will be merged
  1941. * with the existing one. If a CSS property exists in both the new and the old styles,
  1942. * the old one may be overwritten if `$overwrite` is true.
  1943. *
  1944. * For example,
  1945. *
  1946. * ```php
  1947. * Html::addCssStyle($options, 'width: 100px; height: 200px');
  1948. * ```
  1949. *
  1950. * @param array $options the HTML options to be modified.
  1951. * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
  1952. * array (e.g. `['width' => '100px', 'height' => '200px']`).
  1953. * @param bool $overwrite whether to overwrite existing CSS properties if the new style
  1954. * contain them too.
  1955. * @see removeCssStyle()
  1956. * @see cssStyleFromArray()
  1957. * @see cssStyleToArray()
  1958. */
  1959. public static function addCssStyle(&$options, $style, $overwrite = true)
  1960. {
  1961. if (!empty($options['style'])) {
  1962. $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
  1963. $newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
  1964. if (!$overwrite) {
  1965. foreach ($newStyle as $property => $value) {
  1966. if (isset($oldStyle[$property])) {
  1967. unset($newStyle[$property]);
  1968. }
  1969. }
  1970. }
  1971. $style = array_merge($oldStyle, $newStyle);
  1972. }
  1973. $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
  1974. }
  1975. /**
  1976. * Removes the specified CSS style from the HTML options.
  1977. *
  1978. * For example,
  1979. *
  1980. * ```php
  1981. * Html::removeCssStyle($options, ['width', 'height']);
  1982. * ```
  1983. *
  1984. * @param array $options the HTML options to be modified.
  1985. * @param string|array $properties the CSS properties to be removed. You may use a string
  1986. * if you are removing a single property.
  1987. * @see addCssStyle()
  1988. */
  1989. public static function removeCssStyle(&$options, $properties)
  1990. {
  1991. if (!empty($options['style'])) {
  1992. $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
  1993. foreach ((array) $properties as $property) {
  1994. unset($style[$property]);
  1995. }
  1996. $options['style'] = static::cssStyleFromArray($style);
  1997. }
  1998. }
  1999. /**
  2000. * Converts a CSS style array into a string representation.
  2001. *
  2002. * For example,
  2003. *
  2004. * ```php
  2005. * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
  2006. * // will display: 'width: 100px; height: 200px;'
  2007. * ```
  2008. *
  2009. * @param array $style the CSS style array. The array keys are the CSS property names,
  2010. * and the array values are the corresponding CSS property values.
  2011. * @return string the CSS style string. If the CSS style is empty, a null will be returned.
  2012. */
  2013. public static function cssStyleFromArray(array $style)
  2014. {
  2015. $result = '';
  2016. foreach ($style as $name => $value) {
  2017. $result .= "$name: $value; ";
  2018. }
  2019. // return null if empty to avoid rendering the "style" attribute
  2020. return $result === '' ? null : rtrim($result);
  2021. }
  2022. /**
  2023. * Converts a CSS style string into an array representation.
  2024. *
  2025. * The array keys are the CSS property names, and the array values
  2026. * are the corresponding CSS property values.
  2027. *
  2028. * For example,
  2029. *
  2030. * ```php
  2031. * print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
  2032. * // will display: ['width' => '100px', 'height' => '200px']
  2033. * ```
  2034. *
  2035. * @param string $style the CSS style string
  2036. * @return array the array representation of the CSS style
  2037. */
  2038. public static function cssStyleToArray($style)
  2039. {
  2040. $result = [];
  2041. foreach (explode(';', $style) as $property) {
  2042. $property = explode(':', $property);
  2043. if (count($property) > 1) {
  2044. $result[trim($property[0])] = trim($property[1]);
  2045. }
  2046. }
  2047. return $result;
  2048. }
  2049. /**
  2050. * Returns the real attribute name from the given attribute expression.
  2051. *
  2052. * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
  2053. * It is mainly used in tabular data input and/or input of array type. Below are some examples:
  2054. *
  2055. * - `[0]content` is used in tabular data input to represent the "content" attribute
  2056. * for the first model in tabular input;
  2057. * - `dates[0]` represents the first array element of the "dates" attribute;
  2058. * - `[0]dates[0]` represents the first array element of the "dates" attribute
  2059. * for the first model in tabular input.
  2060. *
  2061. * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
  2062. * @param string $attribute the attribute name or expression
  2063. * @return string the attribute name without prefix and suffix.
  2064. * @throws InvalidArgumentException if the attribute name contains non-word characters.
  2065. */
  2066. public static function getAttributeName($attribute)
  2067. {
  2068. if (preg_match(static::$attributeRegex, $attribute, $matches)) {
  2069. return $matches[2];
  2070. }
  2071. throw new InvalidArgumentException('Attribute name must contain word characters only.');
  2072. }
  2073. /**
  2074. * Returns the value of the specified attribute name or expression.
  2075. *
  2076. * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
  2077. * See [[getAttributeName()]] for more details about attribute expression.
  2078. *
  2079. * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
  2080. * the primary value(s) of the AR instance(s) will be returned instead.
  2081. *
  2082. * @param Model $model the model object
  2083. * @param string $attribute the attribute name or expression
  2084. * @return string|array the corresponding attribute value
  2085. * @throws InvalidArgumentException if the attribute name contains non-word characters.
  2086. */
  2087. public static function getAttributeValue($model, $attribute)
  2088. {
  2089. if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
  2090. throw new InvalidArgumentException('Attribute name must contain word characters only.');
  2091. }
  2092. $attribute = $matches[2];
  2093. $value = $model->$attribute;
  2094. if ($matches[3] !== '') {
  2095. foreach (explode('][', trim($matches[3], '[]')) as $id) {
  2096. if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
  2097. $value = $value[$id];
  2098. } else {
  2099. return null;
  2100. }
  2101. }
  2102. }
  2103. // https://github.com/yiisoft/yii2/issues/1457
  2104. if (is_array($value)) {
  2105. foreach ($value as $i => $v) {
  2106. if ($v instanceof ActiveRecordInterface) {
  2107. $v = $v->getPrimaryKey(false);
  2108. $value[$i] = is_array($v) ? json_encode($v) : $v;
  2109. }
  2110. }
  2111. } elseif ($value instanceof ActiveRecordInterface) {
  2112. $value = $value->getPrimaryKey(false);
  2113. return is_array($value) ? json_encode($value) : $value;
  2114. }
  2115. return $value;
  2116. }
  2117. /**
  2118. * Generates an appropriate input name for the specified attribute name or expression.
  2119. *
  2120. * This method generates a name that can be used as the input name to collect user input
  2121. * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
  2122. * of the model and the given attribute name. For example, if the form name of the `Post` model
  2123. * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
  2124. *
  2125. * See [[getAttributeName()]] for explanation of attribute expression.
  2126. *
  2127. * @param Model $model the model object
  2128. * @param string $attribute the attribute name or expression
  2129. * @return string the generated input name
  2130. * @throws InvalidArgumentException if the attribute name contains non-word characters.
  2131. */
  2132. public static function getInputName($model, $attribute)
  2133. {
  2134. $formName = $model->formName();
  2135. if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
  2136. throw new InvalidArgumentException('Attribute name must contain word characters only.');
  2137. }
  2138. $prefix = $matches[1];
  2139. $attribute = $matches[2];
  2140. $suffix = $matches[3];
  2141. if ($formName === '' && $prefix === '') {
  2142. return $attribute . $suffix;
  2143. } elseif ($formName !== '') {
  2144. return $formName . $prefix . "[$attribute]" . $suffix;
  2145. }
  2146. throw new InvalidArgumentException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
  2147. }
  2148. /**
  2149. * Generates an appropriate input ID for the specified attribute name or expression.
  2150. *
  2151. * This method converts the result [[getInputName()]] into a valid input ID.
  2152. * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
  2153. * @param Model $model the model object
  2154. * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
  2155. * @return string the generated input ID
  2156. * @throws InvalidArgumentException if the attribute name contains non-word characters.
  2157. */
  2158. public static function getInputId($model, $attribute)
  2159. {
  2160. $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
  2161. $name = mb_strtolower(static::getInputName($model, $attribute), $charset);
  2162. return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
  2163. }
  2164. /**
  2165. * Escapes regular expression to use in JavaScript.
  2166. * @param string $regexp the regular expression to be escaped.
  2167. * @return string the escaped result.
  2168. * @since 2.0.6
  2169. */
  2170. public static function escapeJsRegularExpression($regexp)
  2171. {
  2172. $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
  2173. $deliminator = substr($pattern, 0, 1);
  2174. $pos = strrpos($pattern, $deliminator, 1);
  2175. $flag = substr($pattern, $pos + 1);
  2176. if ($deliminator !== '/') {
  2177. $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
  2178. } else {
  2179. $pattern = substr($pattern, 0, $pos + 1);
  2180. }
  2181. if (!empty($flag)) {
  2182. $pattern .= preg_replace('/[^igmu]/', '', $flag);
  2183. }
  2184. return $pattern;
  2185. }
  2186. }