Completed
Push — 2.1 ( 0cb910...fafa40 )
by
unknown
40:37 queued 36:49
created

ActiveField::addErrorClassIfNeeded()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
775
            }
776
        }
777
778 1
        $this->parts['{input}'] = $class::widget($config);
779
780 1
        return $this;
781
    }
782
783
    /**
784
     * Adjusts the `for` attribute for the label based on the input options.
785
     * @param array $options the input options.
786
     */
787 18
    protected function adjustLabelFor($options)
788
    {
789 18
        if (!isset($options['id'])) {
790 16
            return;
791
        }
792 2
        $this->_inputId = $options['id'];
793 2
        if (!isset($this->labelOptions['for'])) {
794 2
            $this->labelOptions['for'] = $options['id'];
795
        }
796 2
    }
797
798
    /**
799
     * Checks if client validation enabled for the field.
800
     * @return bool whether client validation enabled for the field.
801
     * @since 2.0.11
802
     */
803
    public function isClientValidationEnabled()
804
    {
805
        return $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation;
806
    }
807
808
    /**
809
     * Checks if AJAX validation enabled for the field.
810
     * @return bool whether AJAX validation enabled for the field.
811
     * @since 2.0.11
812
     */
813
    public function isAjaxValidationEnabled()
814
    {
815
        return $this->enableAjaxValidation || $this->enableAjaxValidation === null && $this->form->enableAjaxValidation;
816
    }
817
818
    /**
819
     * Returns the HTML `id` of the input element of this form field.
820
     * @return string the input id.
821
     * @since 2.0.7
822
     */
823 16
    public function getInputId()
824
    {
825 16
        return $this->_inputId ?: Html::getInputId($this->model, $this->attribute);
826
    }
827
828
    /**
829
     * Adds aria attributes to the input options.
830
     * @param $options array input options
831
     * @since 2.0.11
832
     */
833 15
    protected function addAriaAttributes(&$options)
834
    {
835 15
        if ($this->addAriaAttributes) {
836 15
            if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) {
837 1
                $options['aria-required'] = 'true';
838
            }
839 15
            if (!isset($options['aria-invalid'])) {
840 15
                if ($this->model->hasErrors($this->attribute)) {
841 2
                    $options['aria-invalid'] = 'true';
842
                }
843
            }
844
        }
845 15
    }
846
847
    /**
848
     * Adds validation class to the input options if needed.
849
     * @param $options array input options
850
     * @since 2.0.14
851
     */
852 16
    protected function addErrorClassIfNeeded(&$options)
853
    {
854 16
        if ($this->model->hasErrors($this->attribute)) {
855 4
            Html::addCssClass($options, $this->form->errorCssClass);
856
        }
857 16
    }
858
}
859