ActiveField.php 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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\base\Model;
  12. use yii\helpers\ArrayHelper;
  13. use yii\helpers\Html;
  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']) ? (array) $options['class'] : [];
  230. $class[] = "field-$inputID";
  231. if ($this->model->isAttributeRequired($attribute)) {
  232. $class[] = $this->form->requiredCssClass;
  233. }
  234. $options['class'] = implode(' ', $class);
  235. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_CONTAINER) {
  236. $this->addErrorClassIfNeeded($options);
  237. }
  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. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  344. $this->addErrorClassIfNeeded($options);
  345. }
  346. $this->addAriaAttributes($options);
  347. $this->adjustLabelFor($options);
  348. $this->parts['{input}'] = Html::activeInput($type, $this->model, $this->attribute, $options);
  349. return $this;
  350. }
  351. /**
  352. * Renders a text input.
  353. * This method will generate the `name` and `value` tag attributes automatically for the model attribute
  354. * unless they are explicitly specified in `$options`.
  355. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  356. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  357. *
  358. * The following special options are recognized:
  359. *
  360. * - `maxlength`: int|bool, when `maxlength` is set `true` and the model attribute is validated
  361. * by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
  362. * This is available since version 2.0.3.
  363. *
  364. * Note that if you set a custom `id` for the input element, you may need to adjust the value of [[selectors]] accordingly.
  365. *
  366. * @return $this the field object itself.
  367. */
  368. public function textInput($options = [])
  369. {
  370. $options = array_merge($this->inputOptions, $options);
  371. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  372. $this->addErrorClassIfNeeded($options);
  373. }
  374. $this->addAriaAttributes($options);
  375. $this->adjustLabelFor($options);
  376. $this->parts['{input}'] = Html::activeTextInput($this->model, $this->attribute, $options);
  377. return $this;
  378. }
  379. /**
  380. * Renders a hidden input.
  381. *
  382. * Note that this method is provided for completeness. In most cases because you do not need
  383. * to validate a hidden input, you should not need to use this method. Instead, you should
  384. * use [[\yii\helpers\Html::activeHiddenInput()]].
  385. *
  386. * This method will generate the `name` and `value` tag attributes automatically for the model attribute
  387. * unless they are explicitly specified in `$options`.
  388. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  389. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  390. *
  391. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  392. *
  393. * @return $this the field object itself.
  394. */
  395. public function hiddenInput($options = [])
  396. {
  397. $options = array_merge($this->inputOptions, $options);
  398. $this->adjustLabelFor($options);
  399. $this->parts['{input}'] = Html::activeHiddenInput($this->model, $this->attribute, $options);
  400. return $this;
  401. }
  402. /**
  403. * Renders a password input.
  404. * This method will generate the `name` and `value` tag attributes automatically for the model attribute
  405. * unless they are explicitly specified in `$options`.
  406. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  407. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  408. *
  409. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  410. *
  411. * @return $this the field object itself.
  412. */
  413. public function passwordInput($options = [])
  414. {
  415. $options = array_merge($this->inputOptions, $options);
  416. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  417. $this->addErrorClassIfNeeded($options);
  418. }
  419. $this->addAriaAttributes($options);
  420. $this->adjustLabelFor($options);
  421. $this->parts['{input}'] = Html::activePasswordInput($this->model, $this->attribute, $options);
  422. return $this;
  423. }
  424. /**
  425. * Renders a file input.
  426. * This method will generate the `name` and `value` tag attributes automatically for the model attribute
  427. * unless they are explicitly specified in `$options`.
  428. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  429. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  430. *
  431. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  432. *
  433. * @return $this the field object itself.
  434. */
  435. public function fileInput($options = [])
  436. {
  437. // https://github.com/yiisoft/yii2/pull/795
  438. if ($this->inputOptions !== ['class' => 'form-control']) {
  439. $options = array_merge($this->inputOptions, $options);
  440. }
  441. // https://github.com/yiisoft/yii2/issues/8779
  442. if (!isset($this->form->options['enctype'])) {
  443. $this->form->options['enctype'] = 'multipart/form-data';
  444. }
  445. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  446. $this->addErrorClassIfNeeded($options);
  447. }
  448. $this->addAriaAttributes($options);
  449. $this->adjustLabelFor($options);
  450. $this->parts['{input}'] = Html::activeFileInput($this->model, $this->attribute, $options);
  451. return $this;
  452. }
  453. /**
  454. * Renders a text area.
  455. * The model attribute value will be used as the content in the textarea.
  456. * @param array $options the tag options in terms of name-value pairs. These will be rendered as
  457. * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
  458. *
  459. * If you set a custom `id` for the textarea element, you may need to adjust the [[$selectors]] accordingly.
  460. *
  461. * @return $this the field object itself.
  462. */
  463. public function textarea($options = [])
  464. {
  465. $options = array_merge($this->inputOptions, $options);
  466. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  467. $this->addErrorClassIfNeeded($options);
  468. }
  469. $this->addAriaAttributes($options);
  470. $this->adjustLabelFor($options);
  471. $this->parts['{input}'] = Html::activeTextarea($this->model, $this->attribute, $options);
  472. return $this;
  473. }
  474. /**
  475. * Renders a radio button.
  476. * This method will generate the `checked` tag attribute according to the model attribute value.
  477. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  478. *
  479. * - `uncheck`: string, the value associated with the uncheck state of the radio button. If not set,
  480. * it will take the default value `0`. This method will render a hidden input so that if the radio button
  481. * is not checked and is submitted, the value of this attribute will still be submitted to the server
  482. * via the hidden input. If you do not want any hidden input, you should explicitly set this option as `null`.
  483. * - `label`: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
  484. * 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.
  485. * When this option is specified, the radio button will be enclosed by a label tag. If you do not want any label, you should
  486. * explicitly set this option as `null`.
  487. * - `labelOptions`: array, the HTML attributes for the label tag. This is only used when the `label` option is specified.
  488. *
  489. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  490. * be HTML-encoded using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
  491. *
  492. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  493. *
  494. * @param bool $enclosedByLabel whether to enclose the radio within the label.
  495. * If `true`, the method will still use [[template]] to layout the radio button and the error message
  496. * except that the radio is enclosed by the label tag.
  497. * @return $this the field object itself.
  498. */
  499. public function radio($options = [], $enclosedByLabel = true)
  500. {
  501. if ($enclosedByLabel) {
  502. $this->parts['{input}'] = Html::activeRadio($this->model, $this->attribute, $options);
  503. $this->parts['{label}'] = '';
  504. } else {
  505. if (isset($options['label']) && !isset($this->parts['{label}'])) {
  506. $this->parts['{label}'] = $options['label'];
  507. if (!empty($options['labelOptions'])) {
  508. $this->labelOptions = $options['labelOptions'];
  509. }
  510. }
  511. unset($options['labelOptions']);
  512. $options['label'] = null;
  513. $this->parts['{input}'] = Html::activeRadio($this->model, $this->attribute, $options);
  514. }
  515. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  516. $this->addErrorClassIfNeeded($options);
  517. }
  518. $this->addAriaAttributes($options);
  519. $this->adjustLabelFor($options);
  520. return $this;
  521. }
  522. /**
  523. * Renders a checkbox.
  524. * This method will generate the `checked` tag attribute according to the model attribute value.
  525. * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
  526. *
  527. * - `uncheck`: string, the value associated with the uncheck state of the radio button. If not set,
  528. * it will take the default value `0`. This method will render a hidden input so that if the radio button
  529. * is not checked and is submitted, the value of this attribute will still be submitted to the server
  530. * via the hidden input. If you do not want any hidden input, you should explicitly set this option as `null`.
  531. * - `label`: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
  532. * 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.
  533. * When this option is specified, the checkbox will be enclosed by a label tag. If you do not want any label, you should
  534. * explicitly set this option as `null`.
  535. * - `labelOptions`: array, the HTML attributes for the label tag. This is only used when the `label` option is specified.
  536. *
  537. * The rest of the options will be rendered as the attributes of the resulting tag. The values will
  538. * be HTML-encoded using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
  539. *
  540. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  541. *
  542. * @param bool $enclosedByLabel whether to enclose the checkbox within the label.
  543. * If `true`, the method will still use [[template]] to layout the checkbox and the error message
  544. * except that the checkbox is enclosed by the label tag.
  545. * @return $this the field object itself.
  546. */
  547. public function checkbox($options = [], $enclosedByLabel = true)
  548. {
  549. if ($enclosedByLabel) {
  550. $this->parts['{input}'] = Html::activeCheckbox($this->model, $this->attribute, $options);
  551. $this->parts['{label}'] = '';
  552. } else {
  553. if (isset($options['label']) && !isset($this->parts['{label}'])) {
  554. $this->parts['{label}'] = $options['label'];
  555. if (!empty($options['labelOptions'])) {
  556. $this->labelOptions = $options['labelOptions'];
  557. }
  558. }
  559. unset($options['labelOptions']);
  560. $options['label'] = null;
  561. $this->parts['{input}'] = Html::activeCheckbox($this->model, $this->attribute, $options);
  562. }
  563. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  564. $this->addErrorClassIfNeeded($options);
  565. }
  566. $this->addAriaAttributes($options);
  567. $this->adjustLabelFor($options);
  568. return $this;
  569. }
  570. /**
  571. * Renders a drop-down list.
  572. * The selection of the drop-down list is taken from the value of the model attribute.
  573. * @param array $items the option data items. The array keys are option values, and the array values
  574. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  575. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  576. * If you have a list of data models, you may convert them into the format described above using
  577. * [[ArrayHelper::map()]].
  578. *
  579. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  580. * the labels will also be HTML-encoded.
  581. * @param array $options the tag options in terms of name-value pairs.
  582. *
  583. * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeDropDownList()]].
  584. *
  585. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  586. *
  587. * @return $this the field object itself.
  588. */
  589. public function dropDownList($items, $options = [])
  590. {
  591. $options = array_merge($this->inputOptions, $options);
  592. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  593. $this->addErrorClassIfNeeded($options);
  594. }
  595. $this->addAriaAttributes($options);
  596. $this->adjustLabelFor($options);
  597. $this->parts['{input}'] = Html::activeDropDownList($this->model, $this->attribute, $items, $options);
  598. return $this;
  599. }
  600. /**
  601. * Renders a list box.
  602. * The selection of the list box is taken from the value of the model attribute.
  603. * @param array $items the option data items. The array keys are option values, and the array values
  604. * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
  605. * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
  606. * If you have a list of data models, you may convert them into the format described above using
  607. * [[\yii\helpers\ArrayHelper::map()]].
  608. *
  609. * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
  610. * the labels will also be HTML-encoded.
  611. * @param array $options the tag options in terms of name-value pairs.
  612. *
  613. * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeListBox()]].
  614. *
  615. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  616. *
  617. * @return $this the field object itself.
  618. */
  619. public function listBox($items, $options = [])
  620. {
  621. $options = array_merge($this->inputOptions, $options);
  622. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  623. $this->addErrorClassIfNeeded($options);
  624. }
  625. $this->addAriaAttributes($options);
  626. $this->adjustLabelFor($options);
  627. $this->parts['{input}'] = Html::activeListBox($this->model, $this->attribute, $items, $options);
  628. return $this;
  629. }
  630. /**
  631. * Renders a list of checkboxes.
  632. * A checkbox list allows multiple selection, like [[listBox()]].
  633. * As a result, the corresponding submitted value is an array.
  634. * The selection of the checkbox list is taken from the value of the model attribute.
  635. * @param array $items the data item used to generate the checkboxes.
  636. * The array values are the labels, while the array keys are the corresponding checkbox values.
  637. * @param array $options options (name => config) for the checkbox list.
  638. * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeCheckboxList()]].
  639. * @return $this the field object itself.
  640. */
  641. public function checkboxList($items, $options = [])
  642. {
  643. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  644. $this->addErrorClassIfNeeded($options);
  645. }
  646. $this->addAriaAttributes($options);
  647. $this->adjustLabelFor($options);
  648. $this->_skipLabelFor = true;
  649. $this->parts['{input}'] = Html::activeCheckboxList($this->model, $this->attribute, $items, $options);
  650. return $this;
  651. }
  652. /**
  653. * Renders a list of radio buttons.
  654. * A radio button list is like a checkbox list, except that it only allows single selection.
  655. * The selection of the radio buttons is taken from the value of the model attribute.
  656. * @param array $items the data item used to generate the radio buttons.
  657. * The array values are the labels, while the array keys are the corresponding radio values.
  658. * @param array $options options (name => config) for the radio button list.
  659. * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeRadioList()]].
  660. * @return $this the field object itself.
  661. */
  662. public function radioList($items, $options = [])
  663. {
  664. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  665. $this->addErrorClassIfNeeded($options);
  666. }
  667. $this->addRoleAttributes($options, 'radiogroup');
  668. $this->addAriaAttributes($options);
  669. $this->adjustLabelFor($options);
  670. $this->_skipLabelFor = true;
  671. $this->parts['{input}'] = Html::activeRadioList($this->model, $this->attribute, $items, $options);
  672. return $this;
  673. }
  674. /**
  675. * Renders a widget as the input of the field.
  676. *
  677. * Note that the widget must have both `model` and `attribute` properties. They will
  678. * be initialized with [[model]] and [[attribute]] of this field, respectively.
  679. *
  680. * If you want to use a widget that does not have `model` and `attribute` properties,
  681. * please use [[render()]] instead.
  682. *
  683. * While widgets extending from [[Widget]] work with active field, it is preferred to use
  684. * [[InputWidget]] as a base class.
  685. *
  686. * For example to use the [[MaskedInput]] widget to get some date input, you can use
  687. * the following code, assuming that `$form` is your [[ActiveForm]] instance:
  688. *
  689. * ```php
  690. * $form->field($model, 'date')->widget(\yii\widgets\MaskedInput::className(), [
  691. * 'mask' => '99/99/9999',
  692. * ]);
  693. * ```
  694. *
  695. * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
  696. *
  697. * @param string $class the widget class name.
  698. * @param array $config name-value pairs that will be used to initialize the widget.
  699. * @return $this the field object itself.
  700. * @throws \Exception
  701. */
  702. public function widget($class, $config = [])
  703. {
  704. /* @var $class \yii\base\Widget */
  705. $config['model'] = $this->model;
  706. $config['attribute'] = $this->attribute;
  707. $config['view'] = $this->form->getView();
  708. if (is_subclass_of($class, 'yii\widgets\InputWidget')) {
  709. foreach ($this->inputOptions as $key => $value) {
  710. if (!isset($config['options'][$key])) {
  711. $config['options'][$key] = $value;
  712. }
  713. }
  714. $config['field'] = $this;
  715. if (!isset($config['options'])) {
  716. $config['options'] = [];
  717. }
  718. if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
  719. $this->addErrorClassIfNeeded($config['options']);
  720. }
  721. $this->addAriaAttributes($config['options']);
  722. $this->adjustLabelFor($config['options']);
  723. }
  724. $this->parts['{input}'] = $class::widget($config);
  725. return $this;
  726. }
  727. /**
  728. * Adjusts the `for` attribute for the label based on the input options.
  729. * @param array $options the input options.
  730. */
  731. protected function adjustLabelFor($options)
  732. {
  733. if (!isset($options['id'])) {
  734. return;
  735. }
  736. $this->_inputId = $options['id'];
  737. if (!isset($this->labelOptions['for'])) {
  738. $this->labelOptions['for'] = $options['id'];
  739. }
  740. }
  741. /**
  742. * Returns the JS options for the field.
  743. * @return array the JS options.
  744. */
  745. protected function getClientOptions()
  746. {
  747. $attribute = Html::getAttributeName($this->attribute);
  748. if (!in_array($attribute, $this->model->activeAttributes(), true)) {
  749. return [];
  750. }
  751. $clientValidation = $this->isClientValidationEnabled();
  752. $ajaxValidation = $this->isAjaxValidationEnabled();
  753. if ($clientValidation) {
  754. $validators = [];
  755. foreach ($this->model->getActiveValidators($attribute) as $validator) {
  756. /* @var $validator \yii\validators\Validator */
  757. $js = $validator->clientValidateAttribute($this->model, $attribute, $this->form->getView());
  758. if ($validator->enableClientValidation && $js != '') {
  759. if ($validator->whenClient !== null) {
  760. $js = "if (({$validator->whenClient})(attribute, value)) { $js }";
  761. }
  762. $validators[] = $js;
  763. }
  764. }
  765. }
  766. if (!$ajaxValidation && (!$clientValidation || empty($validators))) {
  767. return [];
  768. }
  769. $options = [];
  770. $inputID = $this->getInputId();
  771. $options['id'] = Html::getInputId($this->model, $this->attribute);
  772. $options['name'] = $this->attribute;
  773. $options['container'] = isset($this->selectors['container']) ? $this->selectors['container'] : ".field-$inputID";
  774. $options['input'] = isset($this->selectors['input']) ? $this->selectors['input'] : "#$inputID";
  775. if (isset($this->selectors['error'])) {
  776. $options['error'] = $this->selectors['error'];
  777. } elseif (isset($this->errorOptions['class'])) {
  778. $options['error'] = '.' . implode('.', preg_split('/\s+/', $this->errorOptions['class'], -1, PREG_SPLIT_NO_EMPTY));
  779. } else {
  780. $options['error'] = isset($this->errorOptions['tag']) ? $this->errorOptions['tag'] : 'span';
  781. }
  782. $options['encodeError'] = !isset($this->errorOptions['encode']) || $this->errorOptions['encode'];
  783. if ($ajaxValidation) {
  784. $options['enableAjaxValidation'] = true;
  785. }
  786. foreach (['validateOnChange', 'validateOnBlur', 'validateOnType', 'validationDelay'] as $name) {
  787. $options[$name] = $this->$name === null ? $this->form->$name : $this->$name;
  788. }
  789. if (!empty($validators)) {
  790. $options['validate'] = new JsExpression('function (attribute, value, messages, deferred, $form) {' . implode('', $validators) . '}');
  791. }
  792. if ($this->addAriaAttributes === false) {
  793. $options['updateAriaInvalid'] = false;
  794. }
  795. // only get the options that are different from the default ones (set in yii.activeForm.js)
  796. return array_diff_assoc($options, [
  797. 'validateOnChange' => true,
  798. 'validateOnBlur' => true,
  799. 'validateOnType' => false,
  800. 'validationDelay' => 500,
  801. 'encodeError' => true,
  802. 'error' => '.help-block',
  803. 'updateAriaInvalid' => true,
  804. ]);
  805. }
  806. /**
  807. * Checks if client validation enabled for the field.
  808. * @return bool
  809. * @since 2.0.11
  810. */
  811. protected function isClientValidationEnabled()
  812. {
  813. return $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation;
  814. }
  815. /**
  816. * Checks if ajax validation enabled for the field.
  817. * @return bool
  818. * @since 2.0.11
  819. */
  820. protected function isAjaxValidationEnabled()
  821. {
  822. return $this->enableAjaxValidation || $this->enableAjaxValidation === null && $this->form->enableAjaxValidation;
  823. }
  824. /**
  825. * Returns the HTML `id` of the input element of this form field.
  826. * @return string the input id.
  827. * @since 2.0.7
  828. */
  829. protected function getInputId()
  830. {
  831. return $this->_inputId ?: Html::getInputId($this->model, $this->attribute);
  832. }
  833. /**
  834. * Adds aria attributes to the input options.
  835. * @param $options array input options
  836. * @since 2.0.11
  837. */
  838. protected function addAriaAttributes(&$options)
  839. {
  840. if ($this->addAriaAttributes) {
  841. if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) {
  842. $options['aria-required'] = 'true';
  843. }
  844. if (!isset($options['aria-invalid']) && $this->model->hasErrors($this->attribute)) {
  845. $options['aria-invalid'] = 'true';
  846. }
  847. }
  848. }
  849. /**
  850. * Add role attributes to the input options
  851. * @param $options array input options
  852. * @param string $role
  853. * @since 2.0.16
  854. */
  855. protected function addRoleAttributes(&$options, $role)
  856. {
  857. if (!isset($options['role'])) {
  858. $options['role'] = $role;
  859. }
  860. }
  861. /**
  862. * Adds validation class to the input options if needed.
  863. * @param $options array input options
  864. * @since 2.0.14
  865. */
  866. protected function addErrorClassIfNeeded(&$options)
  867. {
  868. // Get proper attribute name when attribute name is tabular.
  869. $attributeName = Html::getAttributeName($this->attribute);
  870. if ($this->model->hasErrors($attributeName)) {
  871. Html::addCssClass($options, $this->form->errorCssClass);
  872. }
  873. }
  874. }