BaseHtml.php 102 KB

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