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