Passed
Push — scrutinizer-migrate-to-new-eng... ( 58afd6 )
by Alexander
18:11
created

ActiveField   F

Complexity

Total Complexity 105

Size/Duplication

Total Lines 924
Duplicated Lines 0 %

Test Coverage

Coverage 69.26%

Importance

Changes 0
Metric Value
eloc 257
dl 0
loc 924
ccs 178
cts 257
cp 0.6926
rs 2
c 0
b 0
f 0
wmc 105

28 Methods

Rating   Name   Duplication   Size   Complexity  
A checkboxList() 0 12 2
A getInputId() 0 3 2
A isAjaxValidationEnabled() 0 3 3
A addAriaAttributes() 0 8 6
A addErrorClassIfNeeded() 0 7 2
A adjustLabelFor() 0 8 3
A input() 0 12 2
A __toString() 0 9 2
A radioList() 0 13 2
A fileInput() 0 20 4
A begin() 0 24 6
F getClientOptions() 0 69 21
A checkbox() 0 25 6
A textarea() 0 13 2
A radio() 0 25 6
A listBox() 0 13 2
A dropDownList() 0 13 2
B render() 0 21 7
A hiddenInput() 0 7 1
A isClientValidationEnabled() 0 3 3
A passwordInput() 0 13 2
A error() 0 10 2
A hint() 0 14 3
A end() 0 3 2
A addRoleAttributes() 0 4 2
A widget() 0 21 4
A label() 0 19 4
A textInput() 0 13 2

How to fix   Complexity   

Complex Class

Complex classes like ActiveField often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ActiveField, and based on these observations, apply Extract Interface, too.

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
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
    /**
168
     * PHP magic method that returns the string representation of this object.
169
     * @return string the string representation of this object.
170
     */
171 5
    public function __toString()
172
    {
173
        // __toString cannot throw exception
174
        // use trigger_error to bypass this limitation
175
        try {
176 5
            return $this->render();
177
        } catch (\Exception $e) {
178
            ErrorHandler::convertExceptionToError($e);
179
            return '';
180
        }
181
    }
182
183
    /**
184
     * Renders the whole field.
185
     * This method will generate the label, error tag, input tag and hint tag (if any), and
186
     * assemble them into HTML according to [[template]].
187
     * @param string|callable $content the content within the field container.
188
     * If `null` (not set), the default methods will be called to generate the label, error tag and input tag,
189
     * and use them as the content.
190
     * If a callable, it will be called to generate the content. The signature of the callable should be:
191
     *
192
     * ```php
193
     * function ($field) {
194
     *     return $html;
195
     * }
196
     * ```
197
     *
198
     * @return string the rendering result.
199
     */
200 13
    public function render($content = null)
201
    {
202 13
        if ($content === null) {
203 13
            if (!isset($this->parts['{input}'])) {
204 8
                $this->textInput();
205
            }
206 13
            if (!isset($this->parts['{label}'])) {
207 11
                $this->label();
208
            }
209 13
            if (!isset($this->parts['{error}'])) {
210 11
                $this->error();
211
            }
212 13
            if (!isset($this->parts['{hint}'])) {
213 11
                $this->hint(null);
214
            }
215 13
            $content = strtr($this->template, $this->parts);
216 1
        } elseif (!is_string($content)) {
217 1
            $content = call_user_func($content, $this);
218
        }
219
220 13
        return $this->begin() . "\n" . $content . "\n" . $this->end();
221
    }
222
223
    /**
224
     * Renders the opening tag of the field container.
225
     * @return string the rendering result.
226
     */
227 18
    public function begin()
228
    {
229 18
        if ($this->form->enableClientScript) {
230
            $clientOptions = $this->getClientOptions();
231
            if (!empty($clientOptions)) {
232
                $this->form->attributes[] = $clientOptions;
233
            }
234
        }
235
236 18
        $inputID = $this->getInputId();
237 18
        $attribute = Html::getAttributeName($this->attribute);
238 18
        $options = $this->options;
239 18
        $class = isset($options['class']) ? (array) $options['class'] : [];
240 18
        $class[] = "field-$inputID";
241 18
        if ($this->model->isAttributeRequired($attribute)) {
242 3
            $class[] = $this->form->requiredCssClass;
243
        }
244 18
        $options['class'] = implode(' ', $class);
245 18
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_CONTAINER) {
246 17
            $this->addErrorClassIfNeeded($options);
247
        }
248 18
        $tag = ArrayHelper::remove($options, 'tag', 'div');
249
250 18
        return Html::beginTag($tag, $options);
251
    }
252
253
    /**
254
     * Renders the closing tag of the field container.
255
     * @return string the rendering result.
256
     */
257 14
    public function end()
258
    {
259 14
        return Html::endTag(ArrayHelper::keyExists('tag', $this->options) ? $this->options['tag'] : 'div');
260
    }
261
262
    /**
263
     * Generates a label tag for [[attribute]].
264
     * @param null|string|false $label the label to use. If `null`, the label will be generated via [[Model::getAttributeLabel()]].
265
     * If `false`, the generated field will not contain the label part.
266
     * Note that this will NOT be [[Html::encode()|encoded]].
267
     * @param null|array $options the tag options in terms of name-value pairs. It will be merged with [[labelOptions]].
268
     * The options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded
269
     * using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
270
     * @return $this the field object itself.
271
     */
272 15
    public function label($label = null, $options = [])
273
    {
274 15
        if ($label === false) {
275 4
            $this->parts['{label}'] = '';
276 4
            return $this;
277
        }
278
279 13
        $options = array_merge($this->labelOptions, $options);
280 13
        if ($label !== null) {
0 ignored issues
show
introduced by
The condition $label !== null is always true.
Loading history...
281 2
            $options['label'] = $label;
282
        }
283
284 13
        if ($this->_skipLabelFor) {
285 1
            $options['for'] = null;
286
        }
287
288 13
        $this->parts['{label}'] = Html::activeLabel($this->model, $this->attribute, $options);
289
290 13
        return $this;
291
    }
292
293
    /**
294
     * Generates a tag that contains the first validation error of [[attribute]].
295
     * Note that even if there is no validation error, this method will still return an empty error tag.
296
     * @param array|false $options the tag options in terms of name-value pairs. It will be merged with [[errorOptions]].
297
     * The options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded
298
     * using [[Html::encode()]]. If this parameter is `false`, no error tag will be rendered.
299
     *
300
     * The following options are specially handled:
301
     *
302
     * - `tag`: this specifies the tag name. If not set, `div` will be used.
303
     *   See also [[\yii\helpers\Html::tag()]].
304
     *
305
     * If you set a custom `id` for the error element, you may need to adjust the [[$selectors]] accordingly.
306
     * @see $errorOptions
307
     * @return $this the field object itself.
308
     */
309 13
    public function error($options = [])
310
    {
311 13
        if ($options === false) {
312 2
            $this->parts['{error}'] = '';
313 2
            return $this;
314
        }
315 11
        $options = array_merge($this->errorOptions, $options);
316 11
        $this->parts['{error}'] = Html::error($this->model, $this->attribute, $options);
317
318 11
        return $this;
319
    }
320
321
    /**
322
     * Renders the hint tag.
323
     * @param string|bool $content the hint content.
324
     * If `null`, the hint will be generated via [[Model::getAttributeHint()]].
325
     * If `false`, the generated field will not contain the hint part.
326
     * Note that this will NOT be [[Html::encode()|encoded]].
327
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
328
     * the attributes of the hint tag. The values will be HTML-encoded using [[Html::encode()]].
329
     *
330
     * The following options are specially handled:
331
     *
332
     * - `tag`: this specifies the tag name. If not set, `div` will be used.
333
     *   See also [[\yii\helpers\Html::tag()]].
334
     *
335
     * @return $this the field object itself.
336
     */
337 16
    public function hint($content, $options = [])
338
    {
339 16
        if ($content === false) {
340 3
            $this->parts['{hint}'] = '';
341 3
            return $this;
342
        }
343
344 13
        $options = array_merge($this->hintOptions, $options);
345 13
        if ($content !== null) {
0 ignored issues
show
introduced by
The condition $content !== null is always true.
Loading history...
346 1
            $options['hint'] = $content;
347
        }
348 13
        $this->parts['{hint}'] = Html::activeHint($this->model, $this->attribute, $options);
349
350 13
        return $this;
351
    }
352
353
    /**
354
     * Renders an input tag.
355
     * @param string $type the input type (e.g. `text`, `password`)
356
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
357
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
358
     *
359
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
360
     *
361
     * @return $this the field object itself.
362
     */
363 2
    public function input($type, $options = [])
364
    {
365 2
        $options = array_merge($this->inputOptions, $options);
366 2
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
367
            $this->addErrorClassIfNeeded($options);
368
        }
369
370 2
        $this->addAriaAttributes($options);
371 2
        $this->adjustLabelFor($options);
372 2
        $this->parts['{input}'] = Html::activeInput($type, $this->model, $this->attribute, $options);
373
374 2
        return $this;
375
    }
376
377
    /**
378
     * Renders a text input.
379
     * This method will generate the `name` and `value` tag attributes automatically for the model attribute
380
     * unless they are explicitly specified in `$options`.
381
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
382
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
383
     *
384
     * The following special options are recognized:
385
     *
386
     * - `maxlength`: int|bool, when `maxlength` is set `true` and the model attribute is validated
387
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
388
     *   This is available since version 2.0.3.
389
     *
390
     * Note that if you set a custom `id` for the input element, you may need to adjust the value of [[selectors]] accordingly.
391
     *
392
     * @return $this the field object itself.
393
     */
394 10
    public function textInput($options = [])
395
    {
396 10
        $options = array_merge($this->inputOptions, $options);
397
398 10
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
399 1
            $this->addErrorClassIfNeeded($options);
400
        }
401
402 10
        $this->addAriaAttributes($options);
403 10
        $this->adjustLabelFor($options);
404 10
        $this->parts['{input}'] = Html::activeTextInput($this->model, $this->attribute, $options);
405
406 10
        return $this;
407
    }
408
409
    /**
410
     * Renders a hidden input.
411
     *
412
     * Note that this method is provided for completeness. In most cases because you do not need
413
     * to validate a hidden input, you should not need to use this method. Instead, you should
414
     * use [[\yii\helpers\Html::activeHiddenInput()]].
415
     *
416
     * This method will generate the `name` and `value` tag attributes automatically for the model attribute
417
     * unless they are explicitly specified in `$options`.
418
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
419
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
420
     *
421
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
422
     *
423
     * @return $this the field object itself.
424
     */
425 3
    public function hiddenInput($options = [])
426
    {
427 3
        $options = array_merge($this->inputOptions, $options);
428 3
        $this->adjustLabelFor($options);
429 3
        $this->parts['{input}'] = Html::activeHiddenInput($this->model, $this->attribute, $options);
430
431 3
        return $this;
432
    }
433
434
    /**
435
     * Renders a password input.
436
     * This method will generate the `name` and `value` tag attributes automatically for the model attribute
437
     * unless they are explicitly specified in `$options`.
438
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
439
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
440
     *
441
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
442
     *
443
     * @return $this the field object itself.
444
     */
445
    public function passwordInput($options = [])
446
    {
447
        $options = array_merge($this->inputOptions, $options);
448
449
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
450
            $this->addErrorClassIfNeeded($options);
451
        }
452
453
        $this->addAriaAttributes($options);
454
        $this->adjustLabelFor($options);
455
        $this->parts['{input}'] = Html::activePasswordInput($this->model, $this->attribute, $options);
456
457
        return $this;
458
    }
459
460
    /**
461
     * Renders a file input.
462
     * This method will generate the `name` and `value` tag attributes automatically for the model attribute
463
     * unless they are explicitly specified in `$options`.
464
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
465
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
466
     *
467
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
468
     *
469
     * @return $this the field object itself.
470
     */
471 1
    public function fileInput($options = [])
472
    {
473
        // https://github.com/yiisoft/yii2/pull/795
474 1
        if ($this->inputOptions !== ['class' => 'form-control']) {
475
            $options = array_merge($this->inputOptions, $options);
476
        }
477
        // https://github.com/yiisoft/yii2/issues/8779
478 1
        if (!isset($this->form->options['enctype'])) {
479 1
            $this->form->options['enctype'] = 'multipart/form-data';
480
        }
481
482 1
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
483
            $this->addErrorClassIfNeeded($options);
484
        }
485
486 1
        $this->addAriaAttributes($options);
487 1
        $this->adjustLabelFor($options);
488 1
        $this->parts['{input}'] = Html::activeFileInput($this->model, $this->attribute, $options);
489
490 1
        return $this;
491
    }
492
493
    /**
494
     * Renders a text area.
495
     * The model attribute value will be used as the content in the textarea.
496
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
497
     * the attributes of the resulting tag. The values will be HTML-encoded using [[Html::encode()]].
498
     *
499
     * If you set a custom `id` for the textarea element, you may need to adjust the [[$selectors]] accordingly.
500
     *
501
     * @return $this the field object itself.
502
     */
503
    public function textarea($options = [])
504
    {
505
        $options = array_merge($this->inputOptions, $options);
506
507
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
508
            $this->addErrorClassIfNeeded($options);
509
        }
510
511
        $this->addAriaAttributes($options);
512
        $this->adjustLabelFor($options);
513
        $this->parts['{input}'] = Html::activeTextarea($this->model, $this->attribute, $options);
514
515
        return $this;
516
    }
517
518
    /**
519
     * Renders a radio button.
520
     * This method will generate the `checked` tag attribute according to the model attribute value.
521
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
522
     *
523
     * - `uncheck`: string, the value associated with the uncheck state of the radio button. If not set,
524
     *   it will take the default value `0`. This method will render a hidden input so that if the radio button
525
     *   is not checked and is submitted, the value of this attribute will still be submitted to the server
526
     *   via the hidden input. If you do not want any hidden input, you should explicitly set this option as `null`.
527
     * - `label`: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
528
     *   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.
529
     *   When this option is specified, the radio button will be enclosed by a label tag. If you do not want any label, you should
530
     *   explicitly set this option as `null`.
531
     * - `labelOptions`: array, the HTML attributes for the label tag. This is only used when the `label` option is specified.
532
     *
533
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
534
     * be HTML-encoded using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
535
     *
536
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
537
     *
538
     * @param bool $enclosedByLabel whether to enclose the radio within the label.
539
     * If `true`, the method will still use [[template]] to layout the radio button and the error message
540
     * except that the radio is enclosed by the label tag.
541
     * @return $this the field object itself.
542
     */
543
    public function radio($options = [], $enclosedByLabel = true)
544
    {
545
        if ($enclosedByLabel) {
546
            $this->parts['{input}'] = Html::activeRadio($this->model, $this->attribute, $options);
547
            $this->parts['{label}'] = '';
548
        } else {
549
            if (isset($options['label']) && !isset($this->parts['{label}'])) {
550
                $this->parts['{label}'] = $options['label'];
551
                if (!empty($options['labelOptions'])) {
552
                    $this->labelOptions = $options['labelOptions'];
553
                }
554
            }
555
            unset($options['labelOptions']);
556
            $options['label'] = null;
557
            $this->parts['{input}'] = Html::activeRadio($this->model, $this->attribute, $options);
558
        }
559
560
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
561
            $this->addErrorClassIfNeeded($options);
562
        }
563
564
        $this->addAriaAttributes($options);
565
        $this->adjustLabelFor($options);
566
567
        return $this;
568
    }
569
570
    /**
571
     * Renders a checkbox.
572
     * This method will generate the `checked` tag attribute according to the model attribute value.
573
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
574
     *
575
     * - `uncheck`: string, the value associated with the uncheck state of the radio button. If not set,
576
     *   it will take the default value `0`. This method will render a hidden input so that if the radio button
577
     *   is not checked and is submitted, the value of this attribute will still be submitted to the server
578
     *   via the hidden input. If you do not want any hidden input, you should explicitly set this option as `null`.
579
     * - `label`: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
580
     *   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.
581
     *   When this option is specified, the checkbox will be enclosed by a label tag. If you do not want any label, you should
582
     *   explicitly set this option as `null`.
583
     * - `labelOptions`: array, the HTML attributes for the label tag. This is only used when the `label` option is specified.
584
     *
585
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
586
     * be HTML-encoded using [[Html::encode()]]. If a value is `null`, the corresponding attribute will not be rendered.
587
     *
588
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
589
     *
590
     * @param bool $enclosedByLabel whether to enclose the checkbox within the label.
591
     * If `true`, the method will still use [[template]] to layout the checkbox and the error message
592
     * except that the checkbox is enclosed by the label tag.
593
     * @return $this the field object itself.
594
     */
595
    public function checkbox($options = [], $enclosedByLabel = true)
596
    {
597
        if ($enclosedByLabel) {
598
            $this->parts['{input}'] = Html::activeCheckbox($this->model, $this->attribute, $options);
599
            $this->parts['{label}'] = '';
600
        } else {
601
            if (isset($options['label']) && !isset($this->parts['{label}'])) {
602
                $this->parts['{label}'] = $options['label'];
603
                if (!empty($options['labelOptions'])) {
604
                    $this->labelOptions = $options['labelOptions'];
605
                }
606
            }
607
            unset($options['labelOptions']);
608
            $options['label'] = null;
609
            $this->parts['{input}'] = Html::activeCheckbox($this->model, $this->attribute, $options);
610
        }
611
612
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
613
            $this->addErrorClassIfNeeded($options);
614
        }
615
616
        $this->addAriaAttributes($options);
617
        $this->adjustLabelFor($options);
618
619
        return $this;
620
    }
621
622
    /**
623
     * Renders a drop-down list.
624
     * The selection of the drop-down list 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
     * [[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::activeDropDownList()]].
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
    public function dropDownList($items, $options = [])
642
    {
643
        $options = array_merge($this->inputOptions, $options);
644
645
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
646
            $this->addErrorClassIfNeeded($options);
647
        }
648
649
        $this->addAriaAttributes($options);
650
        $this->adjustLabelFor($options);
651
        $this->parts['{input}'] = Html::activeDropDownList($this->model, $this->attribute, $items, $options);
652
653
        return $this;
654
    }
655
656
    /**
657
     * Renders a list box.
658
     * The selection of the list box is taken from the value of the model attribute.
659
     * @param array $items the option data items. The array keys are option values, and the array values
660
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
661
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
662
     * If you have a list of data models, you may convert them into the format described above using
663
     * [[\yii\helpers\ArrayHelper::map()]].
664
     *
665
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
666
     * the labels will also be HTML-encoded.
667
     * @param array $options the tag options in terms of name-value pairs.
668
     *
669
     * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeListBox()]].
670
     *
671
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
672
     *
673
     * @return $this the field object itself.
674
     */
675 2
    public function listBox($items, $options = [])
676
    {
677 2
        $options = array_merge($this->inputOptions, $options);
678
679 2
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
680
            $this->addErrorClassIfNeeded($options);
681
        }
682
683 2
        $this->addAriaAttributes($options);
684 2
        $this->adjustLabelFor($options);
685 2
        $this->parts['{input}'] = Html::activeListBox($this->model, $this->attribute, $items, $options);
686
687 2
        return $this;
688
    }
689
690
    /**
691
     * Renders a list of checkboxes.
692
     * A checkbox list allows multiple selection, like [[listBox()]].
693
     * As a result, the corresponding submitted value is an array.
694
     * The selection of the checkbox list is taken from the value of the model attribute.
695
     * @param array $items the data item used to generate the checkboxes.
696
     * The array values are the labels, while the array keys are the corresponding checkbox values.
697
     * @param array $options options (name => config) for the checkbox list.
698
     * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeCheckboxList()]].
699
     * @return $this the field object itself.
700
     */
701
    public function checkboxList($items, $options = [])
702
    {
703
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
704
            $this->addErrorClassIfNeeded($options);
705
        }
706
707
        $this->addAriaAttributes($options);
708
        $this->adjustLabelFor($options);
709
        $this->_skipLabelFor = true;
710
        $this->parts['{input}'] = Html::activeCheckboxList($this->model, $this->attribute, $items, $options);
711
712
        return $this;
713
    }
714
715
    /**
716
     * Renders a list of radio buttons.
717
     * A radio button list is like a checkbox list, except that it only allows single selection.
718
     * The selection of the radio buttons is taken from the value of the model attribute.
719
     * @param array $items the data item used to generate the radio buttons.
720
     * The array values are the labels, while the array keys are the corresponding radio values.
721
     * @param array $options options (name => config) for the radio button list.
722
     * For the list of available options please refer to the `$options` parameter of [[\yii\helpers\Html::activeRadioList()]].
723
     * @return $this the field object itself.
724
     */
725 1
    public function radioList($items, $options = [])
726
    {
727 1
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
728
            $this->addErrorClassIfNeeded($options);
729
        }
730
731 1
        $this->addRoleAttributes($options, 'radiogroup');
732 1
        $this->addAriaAttributes($options);
733 1
        $this->adjustLabelFor($options);
734 1
        $this->_skipLabelFor = true;
735 1
        $this->parts['{input}'] = Html::activeRadioList($this->model, $this->attribute, $items, $options);
736
737 1
        return $this;
738
    }
739
740
    /**
741
     * Renders a widget as the input of the field.
742
     *
743
     * Note that the widget must have both `model` and `attribute` properties. They will
744
     * be initialized with [[model]] and [[attribute]] of this field, respectively.
745
     *
746
     * If you want to use a widget that does not have `model` and `attribute` properties,
747
     * please use [[render()]] instead.
748
     *
749
     * For example to use the [[MaskedInput]] widget to get some date input, you can use
750
     * the following code, assuming that `$form` is your [[ActiveForm]] instance:
751
     *
752
     * ```php
753
     * $form->field($model, 'date')->widget(\yii\widgets\MaskedInput::className(), [
754
     *     'mask' => '99/99/9999',
755
     * ]);
756
     * ```
757
     *
758
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
759
     *
760
     * @param string $class the widget class name.
761
     * @param array $config name-value pairs that will be used to initialize the widget.
762
     * @return $this the field object itself.
763
     */
764 1
    public function widget($class, $config = [])
765
    {
766
        /* @var $class \yii\base\Widget */
767 1
        $config['model'] = $this->model;
768 1
        $config['attribute'] = $this->attribute;
769 1
        $config['view'] = $this->form->getView();
770 1
        if (is_subclass_of($class, 'yii\widgets\InputWidget')) {
771 1
            $config['field'] = $this;
772 1
            if (isset($config['options'])) {
773 1
                if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
774
                    $this->addErrorClassIfNeeded($config['options']);
775
                }
776
777 1
                $this->addAriaAttributes($config['options']);
778 1
                $this->adjustLabelFor($config['options']);
779
            }
780
        }
781
782 1
        $this->parts['{input}'] = $class::widget($config);
783
784 1
        return $this;
785
    }
786
787
    /**
788
     * Adjusts the `for` attribute for the label based on the input options.
789
     * @param array $options the input options.
790
     */
791 20
    protected function adjustLabelFor($options)
792
    {
793 20
        if (!isset($options['id'])) {
794 17
            return;
795
        }
796 3
        $this->_inputId = $options['id'];
797 3
        if (!isset($this->labelOptions['for'])) {
798 3
            $this->labelOptions['for'] = $options['id'];
799
        }
800 3
    }
801
802
    /**
803
     * Returns the JS options for the field.
804
     * @return array the JS options.
805
     */
806 5
    protected function getClientOptions()
807
    {
808 5
        $attribute = Html::getAttributeName($this->attribute);
809 5
        if (!in_array($attribute, $this->model->activeAttributes(), true)) {
810 1
            return [];
811
        }
812
813 4
        $clientValidation = $this->isClientValidationEnabled();
814 4
        $ajaxValidation = $this->isAjaxValidationEnabled();
815
816 4
        if ($clientValidation) {
817 3
            $validators = [];
818 3
            foreach ($this->model->getActiveValidators($attribute) as $validator) {
819
                /* @var $validator \yii\validators\Validator */
820 3
                $js = $validator->clientValidateAttribute($this->model, $attribute, $this->form->getView());
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $js is correct as $validator->clientValida...$this->form->getView()) targeting yii\validators\Validator...ientValidateAttribute() seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
821 3
                if ($validator->enableClientValidation && $js != '') {
822 3
                    if ($validator->whenClient !== null) {
823 1
                        $js = "if (({$validator->whenClient})(attribute, value)) { $js }";
824
                    }
825 3
                    $validators[] = $js;
826
                }
827
            }
828
        }
829
830 4
        if (!$ajaxValidation && (!$clientValidation || empty($validators))) {
831 1
            return [];
832
        }
833
834 3
        $options = [];
835
836 3
        $inputID = $this->getInputId();
837 3
        $options['id'] = Html::getInputId($this->model, $this->attribute);
838 3
        $options['name'] = $this->attribute;
839
840 3
        $options['container'] = isset($this->selectors['container']) ? $this->selectors['container'] : ".field-$inputID";
841 3
        $options['input'] = isset($this->selectors['input']) ? $this->selectors['input'] : "#$inputID";
842 3
        if (isset($this->selectors['error'])) {
843
            $options['error'] = $this->selectors['error'];
844 3
        } elseif (isset($this->errorOptions['class'])) {
845 3
            $options['error'] = '.' . implode('.', preg_split('/\s+/', $this->errorOptions['class'], -1, PREG_SPLIT_NO_EMPTY));
0 ignored issues
show
Bug introduced by
It seems like preg_split('/\s+/', $thi...ts\PREG_SPLIT_NO_EMPTY) can also be of type false; however, parameter $pieces of implode() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

845
            $options['error'] = '.' . implode('.', /** @scrutinizer ignore-type */ preg_split('/\s+/', $this->errorOptions['class'], -1, PREG_SPLIT_NO_EMPTY));
Loading history...
846
        } else {
847
            $options['error'] = isset($this->errorOptions['tag']) ? $this->errorOptions['tag'] : 'span';
848
        }
849
850 3
        $options['encodeError'] = !isset($this->errorOptions['encode']) || $this->errorOptions['encode'];
851 3
        if ($ajaxValidation) {
852 2
            $options['enableAjaxValidation'] = true;
853
        }
854 3
        foreach (['validateOnChange', 'validateOnBlur', 'validateOnType', 'validationDelay'] as $name) {
855 3
            $options[$name] = $this->$name === null ? $this->form->$name : $this->$name;
856
        }
857
858 3
        if (!empty($validators)) {
859 3
            $options['validate'] = new JsExpression('function (attribute, value, messages, deferred, $form) {' . implode('', $validators) . '}');
860
        }
861
862 3
        if ($this->addAriaAttributes === false) {
863
            $options['updateAriaInvalid'] = false;
864
        }
865
866
        // only get the options that are different from the default ones (set in yii.activeForm.js)
867 3
        return array_diff_assoc($options, [
868 3
            'validateOnChange' => true,
869
            'validateOnBlur' => true,
870
            'validateOnType' => false,
871
            'validationDelay' => 500,
872
            'encodeError' => true,
873
            'error' => '.help-block',
874
            'updateAriaInvalid' => true,
875
        ]);
876
    }
877
878
    /**
879
     * Checks if client validation enabled for the field.
880
     * @return bool
881
     * @since 2.0.11
882
     */
883 4
    protected function isClientValidationEnabled()
884
    {
885 4
        return $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation;
886
    }
887
888
    /**
889
     * Checks if ajax validation enabled for the field.
890
     * @return bool
891
     * @since 2.0.11
892
     */
893 4
    protected function isAjaxValidationEnabled()
894
    {
895 4
        return $this->enableAjaxValidation || $this->enableAjaxValidation === null && $this->form->enableAjaxValidation;
896
    }
897
898
    /**
899
     * Returns the HTML `id` of the input element of this form field.
900
     * @return string the input id.
901
     * @since 2.0.7
902
     */
903 21
    protected function getInputId()
904
    {
905 21
        return $this->_inputId ?: Html::getInputId($this->model, $this->attribute);
906
    }
907
908
    /**
909
     * Adds aria attributes to the input options.
910
     * @param $options array input options
911
     * @since 2.0.11
912
     */
913 17
    protected function addAriaAttributes(&$options)
914
    {
915 17
        if ($this->addAriaAttributes) {
916 17
            if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) {
917 1
                $options['aria-required'] = 'true';
918
            }
919 17
            if (!isset($options['aria-invalid']) && $this->model->hasErrors($this->attribute)) {
920 2
                $options['aria-invalid'] = 'true';
921
            }
922
        }
923 17
    }
924
925
    /**
926
     * Add role attributes to the input options
927
     * @param $options array input options
928
     * @param string $role
929
     * @since 2.0.16
930
     */
931 1
    protected function addRoleAttributes(&$options, $role)
932
    {
933 1
        if (!isset($options['role'])) {
934 1
            $options['role'] = $role;
935
        }
936 1
    }
937
938
    /**
939
     * Adds validation class to the input options if needed.
940
     * @param $options array input options
941
     * @since 2.0.14
942
     */
943 18
    protected function addErrorClassIfNeeded(&$options)
944
    {
945
        // Get proper attribute name when attribute name is tabular.
946 18
        $attributeName = Html::getAttributeName($this->attribute);
947
948 18
        if ($this->model->hasErrors($attributeName)) {
949 5
            Html::addCssClass($options, $this->form->errorCssClass);
950
        }
951 18
    }
952
}
953