Completed
Push — 2.1 ( 75349f...bf116e )
by Alexander
29:27
created

ActiveField::listBox()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 6
nc 1
nop 2
crap 1
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 4
    public function __toString()
171
    {
172
        // __toString cannot throw exception
173
        // use trigger_error to bypass this limitation
174
        try {
175 4
            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 11
    public function render($content = null)
200
    {
201 11
        if ($content === null) {
202 11
            if (!isset($this->parts['{input}'])) {
203 7
                $this->textInput();
204
            }
205 11
            if (!isset($this->parts['{label}'])) {
206 9
                $this->label();
207
            }
208 11
            if (!isset($this->parts['{error}'])) {
209 9
                $this->error();
210
            }
211 11
            if (!isset($this->parts['{hint}'])) {
212 9
                $this->hint();
213
            }
214 11
            $content = strtr($this->template, $this->parts);
215 1
        } elseif (!is_string($content)) {
216 1
            $content = call_user_func($content, $this);
217
        }
218
219 11
        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 15
    public function begin()
227
    {
228 15
        $this->form->beforeFieldRender($this);
229
230 15
        $inputID = $this->getInputId();
231 15
        $attribute = Html::getAttributeName($this->attribute);
232 15
        $options = $this->options;
233 15
        $class = isset($options['class']) ? (array) $options['class'] : [];
234 15
        $class[] = "field-$inputID";
235 15
        if ($this->model->isAttributeRequired($attribute)) {
236 3
            $class[] = $this->form->requiredCssClass;
237
        }
238 15
        if ($this->model->hasErrors($attribute)) {
239 3
            $class[] = $this->form->errorCssClass;
240
        }
241 15
        $options['class'] = implode(' ', $class);
242 15
        $tag = ArrayHelper::remove($options, 'tag', 'div');
243
244 15
        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 12
    public function end()
252
    {
253 12
        $html = Html::endTag(ArrayHelper::keyExists('tag', $this->options) ? $this->options['tag'] : 'div');
254 12
        $this->form->afterFieldRender($this);
255 12
        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 14
    public function label($label = null, $options = [])
269
    {
270 14
        if ($label === false) {
271 5
            $this->parts['{label}'] = '';
272 5
            return $this;
273
        }
274
275 11
        $options = array_merge($this->labelOptions, $options);
276 11
        if ($label !== null) {
277 2
            $options['label'] = $label;
278
        }
279
280 11
        if ($this->_skipLabelFor) {
281
            $options['for'] = null;
282
        }
283
284 11
        $this->parts['{label}'] = Html::activeLabel($this->model, $this->attribute, $options);
285
286 11
        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 11
    public function error($options = [])
306
    {
307 11
        if ($options === false) {
308 2
            $this->parts['{error}'] = '';
309 2
            return $this;
310
        }
311 9
        $options = array_merge($this->errorOptions, $options);
312 9
        $this->parts['{error}'] = Html::error($this->model, $this->attribute, $options);
313
314 9
        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 14
    public function hint($content = null, $options = [])
334
    {
335 14
        if ($content === false) {
336 3
            $this->parts['{hint}'] = '';
337 3
            return $this;
338
        }
339
340 11
        $options = array_merge($this->hintOptions, $options);
341 11
        if ($content !== null) {
342 1
            $options['hint'] = $content;
343
        }
344 11
        $this->parts['{hint}'] = Html::activeHint($this->model, $this->attribute, $options);
345
346 11
        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
        $this->addAriaAttributes($options);
363 2
        $this->adjustLabelFor($options);
364 2
        $this->parts['{input}'] = Html::activeInput($type, $this->model, $this->attribute, $options);
365
366 2
        return $this;
367
    }
368
369
    /**
370
     * Renders a text input.
371
     * This method will generate the `name` and `value` tag attributes automatically for the model attribute
372
     * unless they are explicitly specified in `$options`.
373
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
374
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
375
     *
376
     * The following special options are recognized:
377
     *
378
     * - `maxlength`: int|bool, when `maxlength` is set `true` and the model attribute is validated
379
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
380
     *   This is available since version 2.0.3.
381
     *
382
     * Note that if you set a custom `id` for the input element, you may need to adjust the value of [[selectors]] accordingly.
383
     *
384
     * @return $this the field object itself.
385
     */
386 9
    public function textInput($options = [])
387
    {
388 9
        $options = array_merge($this->inputOptions, $options);
389 9
        $this->addAriaAttributes($options);
390 9
        $this->adjustLabelFor($options);
391 9
        $this->parts['{input}'] = Html::activeTextInput($this->model, $this->attribute, $options);
392
393 9
        return $this;
394
    }
395
396
    /**
397
     * Renders a hidden input.
398
     *
399
     * Note that this method is provided for completeness. In most cases because you do not need
400
     * to validate a hidden input, you should not need to use this method. Instead, you should
401
     * use [[\yii\helpers\Html::activeHiddenInput()]].
402
     *
403
     * This method will generate the `name` and `value` tag attributes automatically for the model attribute
404
     * unless they are explicitly specified in `$options`.
405
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
406
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
407
     *
408
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
409
     *
410
     * @return $this the field object itself.
411
     */
412 3
    public function hiddenInput($options = [])
413
    {
414 3
        $this->label(false);
415 3
        $options = array_merge($this->inputOptions, $options);
416 3
        $this->adjustLabelFor($options);
417 3
        $this->parts['{input}'] = Html::activeHiddenInput($this->model, $this->attribute, $options);
418
419 3
        return $this;
420
    }
421
422
    /**
423
     * Renders a password input.
424
     * This method will generate the `name` and `value` tag attributes automatically for the model attribute
425
     * unless they are explicitly specified in `$options`.
426
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
427
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
428
     *
429
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
430
     *
431
     * @return $this the field object itself.
432
     */
433
    public function passwordInput($options = [])
434
    {
435
        $options = array_merge($this->inputOptions, $options);
436
        $this->addAriaAttributes($options);
437
        $this->adjustLabelFor($options);
438
        $this->parts['{input}'] = Html::activePasswordInput($this->model, $this->attribute, $options);
439
440
        return $this;
441
    }
442
443
    /**
444
     * Renders a file input.
445
     * This method will generate the `name` and `value` tag attributes automatically for the model attribute
446
     * unless they are explicitly specified in `$options`.
447
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
448
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
449
     *
450
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
451
     *
452
     * @return $this the field object itself.
453
     */
454 1
    public function fileInput($options = [])
455
    {
456
        // https://github.com/yiisoft/yii2/pull/795
457 1
        if ($this->inputOptions !== ['class' => 'form-control']) {
458
            $options = array_merge($this->inputOptions, $options);
459
        }
460
        // https://github.com/yiisoft/yii2/issues/8779
461 1
        if (!isset($this->form->options['enctype'])) {
462 1
            $this->form->options['enctype'] = 'multipart/form-data';
463
        }
464 1
        $this->addAriaAttributes($options);
465 1
        $this->adjustLabelFor($options);
466 1
        $this->parts['{input}'] = Html::activeFileInput($this->model, $this->attribute, $options);
467
468 1
        return $this;
469
    }
470
471
    /**
472
     * Renders a text area.
473
     * The model attribute value will be used as the content in the textarea.
474
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
475
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
476
     *
477
     * If you set a custom `id` for the textarea element, you may need to adjust the [[$selectors]] accordingly.
478
     *
479
     * @return $this the field object itself.
480
     */
481
    public function textarea($options = [])
482
    {
483
        $options = array_merge($this->inputOptions, $options);
484
        $this->addAriaAttributes($options);
485
        $this->adjustLabelFor($options);
486
        $this->parts['{input}'] = Html::activeTextarea($this->model, $this->attribute, $options);
487
488
        return $this;
489
    }
490
491
    /**
492
     * Renders a radio button.
493
     * This method will generate the `checked` tag attribute according to the model attribute value.
494
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
495
     *
496
     * - `uncheck`: string, the value associated with the uncheck state of the radio button. If not set,
497
     *   it will take the default value `0`. This method will render a hidden input so that if the radio button
498
     *   is not checked and is submitted, the value of this attribute will still be submitted to the server
499
     *   via the hidden input. If you do not want any hidden input, you should explicitly set this option as `null`.
500
     * - `label`: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
501
     *   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.
502
     *   When this option is specified, the radio button will be enclosed by a label tag. If you do not want any label, you should
503
     *   explicitly set this option as `null`.
504
     * - `labelOptions`: array, the HTML attributes for the label tag. This is only used when the `label` option is specified.
505
     *
506
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
507
     * be HTML-encoded using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
508
     *
509
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
510
     *
511
     * @param bool $enclosedByLabel whether to enclose the radio within the label.
512
     * If `true`, the method will still use [[template]] to layout the radio button and the error message
513
     * except that the radio is enclosed by the label tag.
514
     * @return $this the field object itself.
515
     */
516
    public function radio($options = [], $enclosedByLabel = true)
517
    {
518
        if ($enclosedByLabel) {
519
            $this->parts['{input}'] = Html::activeRadio($this->model, $this->attribute, $options);
520
            $this->parts['{label}'] = '';
521
        } else {
522
            if (isset($options['label']) && !isset($this->parts['{label}'])) {
523
                $this->parts['{label}'] = $options['label'];
524
                if (!empty($options['labelOptions'])) {
525
                    $this->labelOptions = $options['labelOptions'];
526
                }
527
            }
528
            unset($options['labelOptions']);
529
            $options['label'] = null;
530
            $this->parts['{input}'] = Html::activeRadio($this->model, $this->attribute, $options);
531
        }
532
        $this->addAriaAttributes($options);
533
        $this->adjustLabelFor($options);
534
535
        return $this;
536
    }
537
538
    /**
539
     * Renders a checkbox.
540
     * This method will generate the `checked` tag attribute according to the model attribute value.
541
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
542
     *
543
     * - `uncheck`: string, the value associated with the uncheck state of the radio button. If not set,
544
     *   it will take the default value `0`. This method will render a hidden input so that if the radio button
545
     *   is not checked and is submitted, the value of this attribute will still be submitted to the server
546
     *   via the hidden input. If you do not want any hidden input, you should explicitly set this option as `null`.
547
     * - `label`: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
548
     *   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.
549
     *   When this option is specified, the checkbox will be enclosed by a label tag. If you do not want any label, you should
550
     *   explicitly set this option as `null`.
551
     * - `labelOptions`: array, the HTML attributes for the label tag. This is only used when the `label` option is specified.
552
     *
553
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
554
     * be HTML-encoded using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
555
     *
556
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
557
     *
558
     * @param bool $enclosedByLabel whether to enclose the checkbox within the label.
559
     * If `true`, the method will still use [[template]] to layout the checkbox and the error message
560
     * except that the checkbox is enclosed by the label tag.
561
     * @return $this the field object itself.
562
     */
563
    public function checkbox($options = [], $enclosedByLabel = true)
564
    {
565
        if ($enclosedByLabel) {
566
            $this->parts['{input}'] = Html::activeCheckbox($this->model, $this->attribute, $options);
567
            $this->parts['{label}'] = '';
568
        } else {
569
            if (isset($options['label']) && !isset($this->parts['{label}'])) {
570
                $this->parts['{label}'] = $options['label'];
571
                if (!empty($options['labelOptions'])) {
572
                    $this->labelOptions = $options['labelOptions'];
573
                }
574
            }
575
            unset($options['labelOptions']);
576
            $options['label'] = null;
577
            $this->parts['{input}'] = Html::activeCheckbox($this->model, $this->attribute, $options);
578
        }
579
        $this->addAriaAttributes($options);
580
        $this->adjustLabelFor($options);
581
582
        return $this;
583
    }
584
585
    /**
586
     * Renders a drop-down list.
587
     * The selection of the drop-down list is taken from the value of the model attribute.
588
     * @param array $items the option data items. The array keys are option values, and the array values
589
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
590
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
591
     * If you have a list of data models, you may convert them into the format described above using
592
     * [[ArrayHelper::map()]].
593
     *
594
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
595
     * the labels will also be HTML-encoded.
596
     * @param array $options the tag options in terms of name-value pairs.
597
     *
598
     * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeDropDownList()]].
599
     *
600
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
601
     *
602
     * @return $this the field object itself.
603
     */
604
    public function dropDownList($items, $options = [])
605
    {
606
        $options = array_merge($this->inputOptions, $options);
607
        $this->addAriaAttributes($options);
608
        $this->adjustLabelFor($options);
609
        $this->parts['{input}'] = Html::activeDropDownList($this->model, $this->attribute, $items, $options);
610
611
        return $this;
612
    }
613
614
    /**
615
     * Renders a list box.
616
     * The selection of the list box is taken from the value of the model attribute.
617
     * @param array $items the option data items. The array keys are option values, and the array values
618
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
619
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
620
     * If you have a list of data models, you may convert them into the format described above using
621
     * [[\yii\helpers\ArrayHelper::map()]].
622
     *
623
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
624
     * the labels will also be HTML-encoded.
625
     * @param array $options the tag options in terms of name-value pairs.
626
     *
627
     * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeListBox()]].
628
     *
629
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
630
     *
631
     * @return $this the field object itself.
632
     */
633 2
    public function listBox($items, $options = [])
634
    {
635 2
        $options = array_merge($this->inputOptions, $options);
636 2
        $this->addAriaAttributes($options);
637 2
        $this->adjustLabelFor($options);
638 2
        $this->parts['{input}'] = Html::activeListBox($this->model, $this->attribute, $items, $options);
639
640 2
        return $this;
641
    }
642
643
    /**
644
     * Renders a list of checkboxes.
645
     * A checkbox list allows multiple selection, like [[listBox()]].
646
     * As a result, the corresponding submitted value is an array.
647
     * The selection of the checkbox list is taken from the value of the model attribute.
648
     * @param array $items the data item used to generate the checkboxes.
649
     * The array values are the labels, while the array keys are the corresponding checkbox values.
650
     * @param array $options options (name => config) for the checkbox list.
651
     * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeCheckboxList()]].
652
     * @return $this the field object itself.
653
     */
654
    public function checkboxList($items, $options = [])
655
    {
656
        $this->addAriaAttributes($options);
657
        $this->adjustLabelFor($options);
658
        $this->_skipLabelFor = true;
659
        $this->parts['{input}'] = Html::activeCheckboxList($this->model, $this->attribute, $items, $options);
660
661
        return $this;
662
    }
663
664
    /**
665
     * Renders a list of radio buttons.
666
     * A radio button list is like a checkbox list, except that it only allows single selection.
667
     * The selection of the radio buttons is taken from the value of the model attribute.
668
     * @param array $items the data item used to generate the radio buttons.
669
     * The array values are the labels, while the array keys are the corresponding radio values.
670
     * @param array $options options (name => config) for the radio button list.
671
     * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeRadioList()]].
672
     * @return $this the field object itself.
673
     */
674
    public function radioList($items, $options = [])
675
    {
676
        $this->addAriaAttributes($options);
677
        $this->adjustLabelFor($options);
678
        $this->_skipLabelFor = true;
679
        $this->parts['{input}'] = Html::activeRadioList($this->model, $this->attribute, $items, $options);
680
681
        return $this;
682
    }
683
684
    /**
685
     * Renders a widget as the input of the field.
686
     *
687
     * Note that the widget must have both `model` and `attribute` properties. They will
688
     * be initialized with [[model]] and [[attribute]] of this field, respectively.
689
     *
690
     * If you want to use a widget that does not have `model` and `attribute` properties,
691
     * please use [[render()]] instead.
692
     *
693
     * For example to use the [[MaskedInput]] widget to get some date input, you can use
694
     * the following code, assuming that `$form` is your [[ActiveForm]] instance:
695
     *
696
     * ```php
697
     * $form->field($model, 'date')->widget(\yii\widgets\MaskedInput::class, [
698
     *     'mask' => '99/99/9999',
699
     * ]);
700
     * ```
701
     *
702
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
703
     *
704
     * @param string $class the widget class name.
705
     * @param array $config name-value pairs that will be used to initialize the widget.
706
     * @return $this the field object itself.
707
     */
708 1
    public function widget($class, $config = [])
709
    {
710
        /* @var $class \yii\base\Widget */
711 1
        $config['model'] = $this->model;
712 1
        $config['attribute'] = $this->attribute;
713 1
        $config['view'] = $this->form->getView();
714 1
        if (is_subclass_of($class, 'yii\widgets\InputWidget')) {
715 1
            $config['field'] = $this;
716 1
            if (isset($config['options'])) {
717 1
                $this->addAriaAttributes($config['options']);
718 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...
719
            }
720
        }
721
722 1
        $this->parts['{input}'] = $class::widget($config);
723
724 1
        return $this;
725
    }
726
727
    /**
728
     * Adjusts the `for` attribute for the label based on the input options.
729
     * @param array $options the input options.
730
     */
731 18
    protected function adjustLabelFor($options)
732
    {
733 18
        if (!isset($options['id'])) {
734 15
            return;
735
        }
736 3
        $this->_inputId = $options['id'];
737 3
        if (!isset($this->labelOptions['for'])) {
738 3
            $this->labelOptions['for'] = $options['id'];
739
        }
740 3
    }
741
742
    /**
743
     * Checks if client validation enabled for the field.
744
     * @return bool whether client validation enabled for the field.
745
     * @since 2.0.11
746
     */
747 4
    public function isClientValidationEnabled()
748
    {
749 4
        return $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation;
750
    }
751
752
    /**
753
     * Checks if AJAX validation enabled for the field.
754
     * @return bool whether AJAX validation enabled for the field.
755
     * @since 2.0.11
756
     */
757 4
    public function isAjaxValidationEnabled()
758
    {
759 4
        return $this->enableAjaxValidation || $this->enableAjaxValidation === null && $this->form->enableAjaxValidation;
760
    }
761
762
    /**
763
     * Returns the HTML `id` of the input element of this form field.
764
     * @return string the input id.
765
     * @since 2.0.7
766
     */
767 18
    public function getInputId()
768
    {
769 18
        return $this->_inputId ?: Html::getInputId($this->model, $this->attribute);
770
    }
771
772
    /**
773
     * Adds aria attributes to the input options.
774
     * @param $options array input options
775
     * @since 2.0.11
776
     */
777 15
    protected function addAriaAttributes(&$options)
778
    {
779 15
        if ($this->addAriaAttributes) {
780 15
            if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) {
781 1
                $options['aria-required'] = 'true';
782
            }
783 15
            if (!isset($options['aria-invalid'])) {
784 15
                if ($this->model->hasErrors($this->attribute)) {
785 1
                    $options['aria-invalid'] = 'true';
786
                }
787
            }
788
        }
789 15
    }
790
}
791