BaseHtml.php 103 KB

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