BaseHtml.php 111 KB

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