BaseHtml.php 110 KB

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