ActiveField.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869
  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\widgets;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\ErrorHandler;
  11. use yii\helpers\ArrayHelper;
  12. use yii\helpers\Html;
  13. use yii\base\Model;
  14. use yii\web\JsExpression;
  15. /**
  16. * ActiveField represents a form input field within an [[ActiveForm]].
  17. *
  18. * For more details and usage information on ActiveField, see the [guide article on forms](guide:input-forms).
  19. *
  20. * @author Qiang Xue <qiang.xue@gmail.com>
  21. * @since 2.0
  22. */
  23. class ActiveField extends Component
  24. {
  25. /**
  26. * @var ActiveForm the form that this field is associated with.
  27. */
  28. public $form;
  29. /**
  30. * @var Model the data model that this field is associated with.
  31. */
  32. public $model;
  33. /**
  34. * @var string the model attribute that this field is associated with.
  35. */
  36. public $attribute;
  37. /**
  38. * @var array the HTML attributes (name-value pairs) for the field container tag.
  39. * The values will be HTML-encoded using [[Html::encode()]].
  40. * If a value is `null`, the corresponding attribute will not be rendered.
  41. * The following special options are recognized:
  42. *
  43. * - `tag`: the tag name of the container element. Defaults to `div`. Setting it to `false` will not render a container tag.
  44. * See also [[\yii\helpers\Html::tag()]].
  45. *
  46. * If you set a custom `id` for the container element, you may need to adjust the [[$selectors]] accordingly.
  47. *
  48. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  49. */
  50. public $options = ['class' => 'form-group'];
  51. /**
  52. * @var string the template that is used to arrange the label, the input field, the error message and the hint text.
  53. * The following tokens will be replaced when [[render()]] is called: `{label}`, `{input}`, `{error}` and `{hint}`.
  54. */
  55. public $template = "{label}\n{input}\n{hint}\n{error}";
  56. /**
  57. * @var array the default options for the input tags. The parameter passed to individual input methods
  58. * (e.g. [[textInput()]]) will be merged with this property when rendering the input tag.
  59. *
  60. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  61. *
  62. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  63. */
  64. public $inputOptions = ['class' => 'form-control'];
  65. /**
  66. * @var array the default options for the error tags. The parameter passed to [[error()]] will be
  67. * merged with this property when rendering the error tag.
  68. * The following special options are recognized:
  69. *
  70. * - `tag`: the tag name of the container element. Defaults to `div`. Setting it to `false` will not render a container tag.
  71. * See also [[\yii\helpers\Html::tag()]].
  72. * - `encode`: whether to encode the error output. Defaults to `true`.
  73. *
  74. * If you set a custom `id` for the error element, you may need to adjust the [[$selectors]] accordingly.
  75. *
  76. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  77. */
  78. public $errorOptions = ['class' => 'help-block'];
  79. /**
  80. * @var array the default options for the label tags. The parameter passed to [[label()]] will be
  81. * merged with this property when rendering the label tag.
  82. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  83. */
  84. public $labelOptions = ['class' => 'control-label'];
  85. /**
  86. * @var array the default options for the hint tags. The parameter passed to [[hint()]] will be
  87. * merged with this property when rendering the hint tag.
  88. * The following special options are recognized:
  89. *
  90. * - `tag`: the tag name of the container element. Defaults to `div`. Setting it to `false` will not render a container tag.
  91. * See also [[\yii\helpers\Html::tag()]].
  92. *
  93. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered.
  94. */
  95. public $hintOptions = ['class' => 'hint-block'];
  96. /**
  97. * @var bool whether to enable client-side data validation.
  98. * If not set, it will take the value of [[ActiveForm::enableClientValidation]].
  99. */
  100. public $enableClientValidation;
  101. /**
  102. * @var bool whether to enable AJAX-based data validation.
  103. * If not set, it will take the value of [[ActiveForm::enableAjaxValidation]].
  104. */
  105. public $enableAjaxValidation;
  106. /**
  107. * @var bool whether to perform validation when the value of the input field is changed.
  108. * If not set, it will take the value of [[ActiveForm::validateOnChange]].
  109. */
  110. public $validateOnChange;
  111. /**
  112. * @var bool whether to perform validation when the input field loses focus.
  113. * If not set, it will take the value of [[ActiveForm::validateOnBlur]].
  114. */
  115. public $validateOnBlur;
  116. /**
  117. * @var bool whether to perform validation while the user is typing in the input field.
  118. * If not set, it will take the value of [[ActiveForm::validateOnType]].
  119. * @see validationDelay
  120. */
  121. public $validateOnType;
  122. /**
  123. * @var int number of milliseconds that the validation should be delayed when the user types in the field
  124. * and [[validateOnType]] is set `true`.
  125. * If not set, it will take the value of [[ActiveForm::validationDelay]].
  126. */
  127. public $validationDelay;
  128. /**
  129. * @var array the jQuery selectors for selecting the container, input and error tags.
  130. * The array keys should be `container`, `input`, and/or `error`, and the array values
  131. * are the corresponding selectors. For example, `['input' => '#my-input']`.
  132. *
  133. * The container selector is used under the context of the form, while the input and the error
  134. * selectors are used under the context of the container.
  135. *
  136. * You normally do not need to set this property as the default selectors should work well for most cases.
  137. */
  138. public $selectors = [];
  139. /**
  140. * @var array different parts of the field (e.g. input, label). This will be used together with
  141. * [[template]] to generate the final field HTML code. The keys are the token names in [[template]],
  142. * while the values are the corresponding HTML code. Valid tokens include `{input}`, `{label}` and `{error}`.
  143. * Note that you normally don't need to access this property directly as
  144. * it is maintained by various methods of this class.
  145. */
  146. public $parts = [];
  147. /**
  148. * @var bool adds aria HTML attributes `aria-required` and `aria-invalid` for inputs
  149. * @since 2.0.11
  150. */
  151. public $addAriaAttributes = true;
  152. /**
  153. * @var string this property holds a custom input id if it was set using [[inputOptions]] or in one of the
  154. * `$options` parameters of the `input*` methods.
  155. */
  156. private $_inputId;
  157. /**
  158. * @var bool if "for" field label attribute should be skipped.
  159. */
  160. private $_skipLabelFor = false;
  161. /**
  162. * PHP magic method that returns the string representation of this object.
  163. * @return string the string representation of this object.
  164. */
  165. public function __toString()
  166. {
  167. // __toString cannot throw exception
  168. // use trigger_error to bypass this limitation
  169. try {
  170. return $this->render();
  171. } catch (\Exception $e) {
  172. ErrorHandler::convertExceptionToError($e);
  173. return '';
  174. }
  175. }
  176. /**
  177. * Renders the whole field.
  178. * This method will generate the label, error tag, input tag and hint tag (if any), and
  179. * assemble them into HTML according to [[template]].
  180. * @param string|callable $content the content within the field container.
  181. * If `null` (not set), the default methods will be called to generate the label, error tag and input tag,
  182. * and use them as the content.
  183. * If a callable, it will be called to generate the content. The signature of the callable should be:
  184. *
  185. * ```php
  186. * function ($field) {
  187. * return $html;
  188. * }
  189. * ```
  190. *
  191. * @return string the rendering result.
  192. */
  193. public function render($content = null)
  194. {
  195. if ($content === null) {
  196. if (!isset($this->parts['{input}'])) {
  197. $this->textInput();
  198. }
  199. if (!isset($this->parts['{label}'])) {
  200. $this->label();
  201. }
  202. if (!isset($this->parts['{error}'])) {
  203. $this->error();
  204. }
  205. if (!isset($this->parts['{hint}'])) {
  206. $this->hint(null);
  207. }
  208. $content = strtr($this->template, $this->parts);
  209. } elseif (!is_string($content)) {
  210. $content = call_user_func($content, $this);
  211. }
  212. return $this->begin() . "\n" . $content . "\n" . $this->end();
  213. }
  214. /**
  215. * Renders the opening tag of the field container.
  216. * @return string the rendering result.
  217. */
  218. public function begin()
  219. {
  220. if ($this->form->enableClientScript) {
  221. $clientOptions = $this->getClientOptions();
  222. if (!empty($clientOptions)) {
  223. $this->form->attributes[] = $clientOptions;
  224. }
  225. }
  226. $inputID = $this->getInputId();
  227. $attribute = Html::getAttributeName($this->attribute);
  228. $options = $this->options;
  229. $class = isset($options['class']) ? [$options['class']] : [];
  230. $class[] = "field-$inputID";
  231. if ($this->model->isAttributeRequired($attribute)) {
  232. $class[] = $this->form->requiredCssClass;
  233. }
  234. if ($this->model->hasErrors($attribute)) {
  235. $class[] = $this->form->errorCssClass;
  236. }
  237. $options['class'] = implode(' ', $class);
  238. $tag = ArrayHelper::remove($options, 'tag', 'div');
  239. return Html::beginTag($tag, $options);
  240. }
  241. /**
  242. * Renders the closing tag of the field container.
  243. * @return string the rendering result.
  244. */
  245. public function end()
  246. {
  247. return Html::endTag(ArrayHelper::keyExists('tag', $this->options) ? $this->options['tag'] : 'div');
  248. }
  249. /**
  250. * Generates a label tag for [[attribute]].
  251. * @param null|string|false $label the label to use. If `null`, the label will be generated via [[Model::getAttributeLabel()]].
  252. * If `false`, the generated field will not contain the label part.
  253. * Note that this will NOT be [[Html::encode()|encoded]].
  254. * @param null|array $options the tag options in terms of name-value pairs. It will be merged with [[labelOptions]].
  255. * The options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded
  256. * using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
  257. * @return $this the field object itself.
  258. */
  259. public function label($label = null, $options = [])
  260. {
  261. if ($label === false) {
  262. $this->parts['{label}'] = '';
  263. return $this;
  264. }
  265. $options = array_merge($this->labelOptions, $options);
  266. if ($label !== null) {
  267. $options['label'] = $label;
  268. }
  269. if ($this->_skipLabelFor) {
  270. $options['for'] = null;
  271. }
  272. $this->parts['{label}'] = Html::activeLabel($this->model, $this->attribute, $options);
  273. return $this;
  274. }
  275. /**
  276. * Generates a tag that contains the first validation error of [[attribute]].
  277. * Note that even if there is no validation error, this method will still return an empty error tag.
  278. * @param array|false $options the tag options in terms of name-value pairs. It will be merged with [[errorOptions]].
  279. * The options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded
  280. * using [[Html::encode()]]. If this parameter is `false`, no error tag will be rendered.
  281. *
  282. * The following options are specially handled:
  283. *
  284. * - `tag`: this specifies the tag name. If not set, `div` will be used.
  285. * See also [[\yii\helpers\Html::tag()]].
  286. *
  287. * If you set a custom `id` for the error element, you may need to adjust the [[$selectors]] accordingly.
  288. * @see $errorOptions
  289. * @return $this the field object itself.
  290. */
  291. public function error($options = [])
  292. {
  293. if ($options === false) {
  294. $this->parts['{error}'] = '';
  295. return $this;
  296. }
  297. $options = array_merge($this->errorOptions, $options);
  298. $this->parts['{error}'] = Html::error($this->model, $this->attribute, $options);
  299. return $this;
  300. }
  301. /**
  302. * Renders the hint tag.
  303. * @param string|bool $content the hint content.
  304. * If `null`, the hint will be generated via [[Model::getAttributeHint()]].
  305. * If `false`, the generated field will not contain the hint part.
  306. * Note that this will NOT be [[Html::encode()|encoded]].
  307. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  308. * the attributes of the hint tag. The values will be HTML-encoded using [[Html::encode()]].
  309. *
  310. * The following options are specially handled:
  311. *
  312. * - `tag`: this specifies the tag name. If not set, `div` will be used.
  313. * See also [[\yii\helpers\Html::tag()]].
  314. *
  315. * @return $this the field object itself.
  316. */
  317. public function hint($content, $options = [])
  318. {
  319. if ($content === false) {
  320. $this->parts['{hint}'] = '';
  321. return $this;
  322. }
  323. $options = array_merge($this->hintOptions, $options);
  324. if ($content !== null) {
  325. $options['hint'] = $content;
  326. }
  327. $this->parts['{hint}'] = Html::activeHint($this->model, $this->attribute, $options);
  328. return $this;
  329. }
  330. /**
  331. * Renders an input tag.
  332. * @param string $type the input type (e.g. `text`, `password`)
  333. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  334. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  335. *
  336. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  337. *
  338. * @return $this the field object itself.
  339. */
  340. public function input($type, $options = [])
  341. {
  342. $options = array_merge($this->inputOptions, $options);
  343. $this->addAriaAttributes($options);
  344. $this->adjustLabelFor($options);
  345. $this->parts['{input}'] = Html::activeInput($type, $this->model, $this->attribute, $options);
  346. return $this;
  347. }
  348. /**
  349. * Renders a text input.
  350. * This method will generate the `name` and `value` tag attributes automatically for the model attribute
  351. * unless they are explicitly specified in `$options`.
  352. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  353. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  354. *
  355. * The following special options are recognized:
  356. *
  357. * - `maxlength`: int|bool, when `maxlength` is set `true` and the model attribute is validated
  358. * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  359. * This is available since version 2.0.3.
  360. *
  361. * Note that if you set a custom `id` for the input element, you may need to adjust the value of [[selectors]] accordingly.
  362. *
  363. * @return $this the field object itself.
  364. */
  365. public function textInput($options = [])
  366. {
  367. $options = array_merge($this->inputOptions, $options);
  368. $this->addAriaAttributes($options);
  369. $this->adjustLabelFor($options);
  370. $this->parts['{input}'] = Html::activeTextInput($this->model, $this->attribute, $options);
  371. return $this;
  372. }
  373. /**
  374. * Renders a hidden input.
  375. *
  376. * Note that this method is provided for completeness. In most cases because you do not need
  377. * to validate a hidden input, you should not need to use this method. Instead, you should
  378. * use [[\yii\helpers\Html::activeHiddenInput()]].
  379. *
  380. * This method will generate the `name` and `value` tag attributes automatically for the model attribute
  381. * unless they are explicitly specified in `$options`.
  382. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  383. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  384. *
  385. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  386. *
  387. * @return $this the field object itself.
  388. */
  389. public function hiddenInput($options = [])
  390. {
  391. $options = array_merge($this->inputOptions, $options);
  392. $this->adjustLabelFor($options);
  393. $this->parts['{input}'] = Html::activeHiddenInput($this->model, $this->attribute, $options);
  394. return $this;
  395. }
  396. /**
  397. * Renders a password input.
  398. * This method will generate the `name` and `value` tag attributes automatically for the model attribute
  399. * unless they are explicitly specified in `$options`.
  400. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  401. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  402. *
  403. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  404. *
  405. * @return $this the field object itself.
  406. */
  407. public function passwordInput($options = [])
  408. {
  409. $options = array_merge($this->inputOptions, $options);
  410. $this->addAriaAttributes($options);
  411. $this->adjustLabelFor($options);
  412. $this->parts['{input}'] = Html::activePasswordInput($this->model, $this->attribute, $options);
  413. return $this;
  414. }
  415. /**
  416. * Renders a file input.
  417. * This method will generate the `name` and `value` tag attributes automatically for the model attribute
  418. * unless they are explicitly specified in `$options`.
  419. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  420. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  421. *
  422. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  423. *
  424. * @return $this the field object itself.
  425. */
  426. public function fileInput($options = [])
  427. {
  428. // https://github.com/yiisoft/yii2/pull/795
  429. if ($this->inputOptions !== ['class' => 'form-control']) {
  430. $options = array_merge($this->inputOptions, $options);
  431. }
  432. // https://github.com/yiisoft/yii2/issues/8779
  433. if (!isset($this->form->options['enctype'])) {
  434. $this->form->options['enctype'] = 'multipart/form-data';
  435. }
  436. $this->addAriaAttributes($options);
  437. $this->adjustLabelFor($options);
  438. $this->parts['{input}'] = Html::activeFileInput($this->model, $this->attribute, $options);
  439. return $this;
  440. }
  441. /**
  442. * Renders a text area.
  443. * The model attribute value will be used as the content in the textarea.
  444. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  445. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  446. *
  447. * If you set a custom `id` for the textarea element, you may need to adjust the [[$selectors]] accordingly.
  448. *
  449. * @return $this the field object itself.
  450. */
  451. public function textarea($options = [])
  452. {
  453. $options = array_merge($this->inputOptions, $options);
  454. $this->addAriaAttributes($options);
  455. $this->adjustLabelFor($options);
  456. $this->parts['{input}'] = Html::activeTextarea($this->model, $this->attribute, $options);
  457. return $this;
  458. }
  459. /**
  460. * Renders a radio button.
  461. * This method will generate the `checked` tag attribute according to the model attribute value.
  462. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  463. *
  464. * - `uncheck`: string, the value associated with the uncheck state of the radio button. If not set,
  465. * it will take the default value `0`. This method will render a hidden input so that if the radio button
  466. * is not checked and is submitted, the value of this attribute will still be submitted to the server
  467. * via the hidden input. If you do not want any hidden input, you should explicitly set this option as `null`.
  468. * - `label`: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
  469. * in HTML code such as an image tag. If this is coming from end users, you should [[Html::encode()|encode]] it to prevent XSS attacks.
  470. * When this option is specified, the radio button will be enclosed by a label tag. If you do not want any label, you should
  471. * explicitly set this option as `null`.
  472. * - `labelOptions`: array, the HTML attributes for the label tag. This is only used when the `label` option is specified.
  473. *
  474. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  475. * be HTML-encoded using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
  476. *
  477. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  478. *
  479. * @param bool $enclosedByLabel whether to enclose the radio within the label.
  480. * If `true`, the method will still use [[template]] to layout the radio button and the error message
  481. * except that the radio is enclosed by the label tag.
  482. * @return $this the field object itself.
  483. */
  484. public function radio($options = [], $enclosedByLabel = true)
  485. {
  486. if ($enclosedByLabel) {
  487. $this->parts['{input}'] = Html::activeRadio($this->model, $this->attribute, $options);
  488. $this->parts['{label}'] = '';
  489. } else {
  490. if (isset($options['label']) && !isset($this->parts['{label}'])) {
  491. $this->parts['{label}'] = $options['label'];
  492. if (!empty($options['labelOptions'])) {
  493. $this->labelOptions = $options['labelOptions'];
  494. }
  495. }
  496. unset($options['labelOptions']);
  497. $options['label'] = null;
  498. $this->parts['{input}'] = Html::activeRadio($this->model, $this->attribute, $options);
  499. }
  500. $this->addAriaAttributes($options);
  501. $this->adjustLabelFor($options);
  502. return $this;
  503. }
  504. /**
  505. * Renders a checkbox.
  506. * This method will generate the `checked` tag attribute according to the model attribute value.
  507. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  508. *
  509. * - `uncheck`: string, the value associated with the uncheck state of the radio button. If not set,
  510. * it will take the default value `0`. This method will render a hidden input so that if the radio button
  511. * is not checked and is submitted, the value of this attribute will still be submitted to the server
  512. * via the hidden input. If you do not want any hidden input, you should explicitly set this option as `null`.
  513. * - `label`: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
  514. * in HTML code such as an image tag. If this is coming from end users, you should [[Html::encode()|encode]] it to prevent XSS attacks.
  515. * When this option is specified, the checkbox will be enclosed by a label tag. If you do not want any label, you should
  516. * explicitly set this option as `null`.
  517. * - `labelOptions`: array, the HTML attributes for the label tag. This is only used when the `label` option is specified.
  518. *
  519. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  520. * be HTML-encoded using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
  521. *
  522. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  523. *
  524. * @param bool $enclosedByLabel whether to enclose the checkbox within the label.
  525. * If `true`, the method will still use [[template]] to layout the checkbox and the error message
  526. * except that the checkbox is enclosed by the label tag.
  527. * @return $this the field object itself.
  528. */
  529. public function checkbox($options = [], $enclosedByLabel = true)
  530. {
  531. if ($enclosedByLabel) {
  532. $this->parts['{input}'] = Html::activeCheckbox($this->model, $this->attribute, $options);
  533. $this->parts['{label}'] = '';
  534. } else {
  535. if (isset($options['label']) && !isset($this->parts['{label}'])) {
  536. $this->parts['{label}'] = $options['label'];
  537. if (!empty($options['labelOptions'])) {
  538. $this->labelOptions = $options['labelOptions'];
  539. }
  540. }
  541. unset($options['labelOptions']);
  542. $options['label'] = null;
  543. $this->parts['{input}'] = Html::activeCheckbox($this->model, $this->attribute, $options);
  544. }
  545. $this->addAriaAttributes($options);
  546. $this->adjustLabelFor($options);
  547. return $this;
  548. }
  549. /**
  550. * Renders a drop-down list.
  551. * The selection of the drop-down list is taken from the value of the model attribute.
  552. * @param array $items the option data items. The array keys are option values, and the array values
  553. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  554. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  555. * If you have a list of data models, you may convert them into the format described above using
  556. * [[ArrayHelper::map()]].
  557. *
  558. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  559. * the labels will also be HTML-encoded.
  560. * @param array $options the tag options in terms of name-value pairs.
  561. *
  562. * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeDropDownList()]].
  563. *
  564. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  565. *
  566. * @return $this the field object itself.
  567. */
  568. public function dropDownList($items, $options = [])
  569. {
  570. $options = array_merge($this->inputOptions, $options);
  571. $this->addAriaAttributes($options);
  572. $this->adjustLabelFor($options);
  573. $this->parts['{input}'] = Html::activeDropDownList($this->model, $this->attribute, $items, $options);
  574. return $this;
  575. }
  576. /**
  577. * Renders a list box.
  578. * The selection of the list box is taken from the value of the model attribute.
  579. * @param array $items the option data items. The array keys are option values, and the array values
  580. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  581. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  582. * If you have a list of data models, you may convert them into the format described above using
  583. * [[\yii\helpers\ArrayHelper::map()]].
  584. *
  585. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  586. * the labels will also be HTML-encoded.
  587. * @param array $options the tag options in terms of name-value pairs.
  588. *
  589. * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeListBox()]].
  590. *
  591. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  592. *
  593. * @return $this the field object itself.
  594. */
  595. public function listBox($items, $options = [])
  596. {
  597. $options = array_merge($this->inputOptions, $options);
  598. $this->addAriaAttributes($options);
  599. $this->adjustLabelFor($options);
  600. $this->parts['{input}'] = Html::activeListBox($this->model, $this->attribute, $items, $options);
  601. return $this;
  602. }
  603. /**
  604. * Renders a list of checkboxes.
  605. * A checkbox list allows multiple selection, like [[listBox()]].
  606. * As a result, the corresponding submitted value is an array.
  607. * The selection of the checkbox list is taken from the value of the model attribute.
  608. * @param array $items the data item used to generate the checkboxes.
  609. * The array values are the labels, while the array keys are the corresponding checkbox values.
  610. * @param array $options options (name => config) for the checkbox list.
  611. * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeCheckboxList()]].
  612. * @return $this the field object itself.
  613. */
  614. public function checkboxList($items, $options = [])
  615. {
  616. $this->addAriaAttributes($options);
  617. $this->adjustLabelFor($options);
  618. $this->_skipLabelFor = true;
  619. $this->parts['{input}'] = Html::activeCheckboxList($this->model, $this->attribute, $items, $options);
  620. return $this;
  621. }
  622. /**
  623. * Renders a list of radio buttons.
  624. * A radio button list is like a checkbox list, except that it only allows single selection.
  625. * The selection of the radio buttons is taken from the value of the model attribute.
  626. * @param array $items the data item used to generate the radio buttons.
  627. * The array values are the labels, while the array keys are the corresponding radio values.
  628. * @param array $options options (name => config) for the radio button list.
  629. * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeRadioList()]].
  630. * @return $this the field object itself.
  631. */
  632. public function radioList($items, $options = [])
  633. {
  634. $this->addAriaAttributes($options);
  635. $this->adjustLabelFor($options);
  636. $this->_skipLabelFor = true;
  637. $this->parts['{input}'] = Html::activeRadioList($this->model, $this->attribute, $items, $options);
  638. return $this;
  639. }
  640. /**
  641. * Renders a widget as the input of the field.
  642. *
  643. * Note that the widget must have both `model` and `attribute` properties. They will
  644. * be initialized with [[model]] and [[attribute]] of this field, respectively.
  645. *
  646. * If you want to use a widget that does not have `model` and `attribute` properties,
  647. * please use [[render()]] instead.
  648. *
  649. * For example to use the [[MaskedInput]] widget to get some date input, you can use
  650. * the following code, assuming that `$form` is your [[ActiveForm]] instance:
  651. *
  652. * ```php
  653. * $form->field($model, 'date')->widget(\yii\widgets\MaskedInput::className(), [
  654. * 'mask' => '99/99/9999',
  655. * ]);
  656. * ```
  657. *
  658. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  659. *
  660. * @param string $class the widget class name.
  661. * @param array $config name-value pairs that will be used to initialize the widget.
  662. * @return $this the field object itself.
  663. */
  664. public function widget($class, $config = [])
  665. {
  666. /* @var $class \yii\base\Widget */
  667. $config['model'] = $this->model;
  668. $config['attribute'] = $this->attribute;
  669. $config['view'] = $this->form->getView();
  670. if (is_subclass_of($class, 'yii\widgets\InputWidget')) {
  671. $config['field'] = $this;
  672. if (isset($config['options'])) {
  673. $this->addAriaAttributes($config['options']);
  674. $this->adjustLabelFor($config['options']);
  675. }
  676. }
  677. $this->parts['{input}'] = $class::widget($config);
  678. return $this;
  679. }
  680. /**
  681. * Adjusts the `for` attribute for the label based on the input options.
  682. * @param array $options the input options.
  683. */
  684. protected function adjustLabelFor($options)
  685. {
  686. if (!isset($options['id'])) {
  687. return;
  688. }
  689. $this->_inputId = $options['id'];
  690. if (!isset($this->labelOptions['for'])) {
  691. $this->labelOptions['for'] = $options['id'];
  692. }
  693. }
  694. /**
  695. * Returns the JS options for the field.
  696. * @return array the JS options.
  697. */
  698. protected function getClientOptions()
  699. {
  700. $attribute = Html::getAttributeName($this->attribute);
  701. if (!in_array($attribute, $this->model->activeAttributes(), true)) {
  702. return [];
  703. }
  704. $clientValidation = $this->isClientValidationEnabled();
  705. $ajaxValidation = $this->isAjaxValidationEnabled();
  706. if ($clientValidation) {
  707. $validators = [];
  708. foreach ($this->model->getActiveValidators($attribute) as $validator) {
  709. /* @var $validator \yii\validators\Validator */
  710. $js = $validator->clientValidateAttribute($this->model, $attribute, $this->form->getView());
  711. if ($validator->enableClientValidation && $js != '') {
  712. if ($validator->whenClient !== null) {
  713. $js = "if (({$validator->whenClient})(attribute, value)) { $js }";
  714. }
  715. $validators[] = $js;
  716. }
  717. }
  718. }
  719. if (!$ajaxValidation && (!$clientValidation || empty($validators))) {
  720. return [];
  721. }
  722. $options = [];
  723. $inputID = $this->getInputId();
  724. $options['id'] = Html::getInputId($this->model, $this->attribute);
  725. $options['name'] = $this->attribute;
  726. $options['container'] = isset($this->selectors['container']) ? $this->selectors['container'] : ".field-$inputID";
  727. $options['input'] = isset($this->selectors['input']) ? $this->selectors['input'] : "#$inputID";
  728. if (isset($this->selectors['error'])) {
  729. $options['error'] = $this->selectors['error'];
  730. } elseif (isset($this->errorOptions['class'])) {
  731. $options['error'] = '.' . implode('.', preg_split('/\s+/', $this->errorOptions['class'], -1, PREG_SPLIT_NO_EMPTY));
  732. } else {
  733. $options['error'] = isset($this->errorOptions['tag']) ? $this->errorOptions['tag'] : 'span';
  734. }
  735. $options['encodeError'] = !isset($this->errorOptions['encode']) || $this->errorOptions['encode'];
  736. if ($ajaxValidation) {
  737. $options['enableAjaxValidation'] = true;
  738. }
  739. foreach (['validateOnChange', 'validateOnBlur', 'validateOnType', 'validationDelay'] as $name) {
  740. $options[$name] = $this->$name === null ? $this->form->$name : $this->$name;
  741. }
  742. if (!empty($validators)) {
  743. $options['validate'] = new JsExpression("function (attribute, value, messages, deferred, \$form) {" . implode('', $validators) . '}');
  744. }
  745. if ($this->addAriaAttributes === false) {
  746. $options['updateAriaInvalid'] = false;
  747. }
  748. // only get the options that are different from the default ones (set in yii.activeForm.js)
  749. return array_diff_assoc($options, [
  750. 'validateOnChange' => true,
  751. 'validateOnBlur' => true,
  752. 'validateOnType' => false,
  753. 'validationDelay' => 500,
  754. 'encodeError' => true,
  755. 'error' => '.help-block',
  756. 'updateAriaInvalid' => true,
  757. ]);
  758. }
  759. /**
  760. * Checks if client validation enabled for the field
  761. * @return bool
  762. * @since 2.0.11
  763. */
  764. protected function isClientValidationEnabled()
  765. {
  766. return $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation;
  767. }
  768. /**
  769. * Checks if ajax validation enabled for the field
  770. * @return bool
  771. * @since 2.0.11
  772. */
  773. protected function isAjaxValidationEnabled()
  774. {
  775. return $this->enableAjaxValidation || $this->enableAjaxValidation === null && $this->form->enableAjaxValidation;
  776. }
  777. /**
  778. * Returns the HTML `id` of the input element of this form field.
  779. * @return string the input id.
  780. * @since 2.0.7
  781. */
  782. protected function getInputId()
  783. {
  784. return $this->_inputId ?: Html::getInputId($this->model, $this->attribute);
  785. }
  786. /**
  787. * Adds aria attributes to the input options
  788. * @param $options array input options
  789. * @since 2.0.11
  790. */
  791. protected function addAriaAttributes(&$options)
  792. {
  793. if ($this->addAriaAttributes) {
  794. if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) {
  795. $options['aria-required'] = 'true';
  796. }
  797. if (!isset($options['aria-invalid'])) {
  798. if ($this->model->hasErrors($this->attribute)) {
  799. $options['aria-invalid'] = 'true';
  800. }
  801. }
  802. }
  803. }
  804. }