Completed
Push — aria-required-and-aria-invalid... ( ed8acc )
by Alexander
33:01 queued 29:32
created

ActiveField::radioList()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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