Completed
Push — 15476-add-option-to-change-val... ( 21fb7c...e0a164 )
by Alexander
10:35
created

ActiveField::widget()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 4.0072

Importance

Changes 0
Metric Value
dl 0
loc 22
ccs 12
cts 13
cp 0.9231
rs 8.9197
c 0
b 0
f 0
cc 4
eloc 13
nc 4
nop 2
crap 4.0072
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 12
    public function render($content = null)
201
    {
202 12
        if ($content === null) {
203 12
            if (!isset($this->parts['{input}'])) {
204 8
                $this->textInput();
205
            }
206 12
            if (!isset($this->parts['{label}'])) {
207 10
                $this->label();
208
            }
209 12
            if (!isset($this->parts['{error}'])) {
210 10
                $this->error();
211
            }
212 12
            if (!isset($this->parts['{hint}'])) {
213 10
                $this->hint(null);
214
            }
215 12
            $content = strtr($this->template, $this->parts);
216 1
        } elseif (!is_string($content)) {
217 1
            $content = call_user_func($content, $this);
218
        }
219
220 12
        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 16
    public function begin()
228
    {
229 16
        if ($this->form->enableClientScript) {
230
            $clientOptions = $this->getClientOptions();
231
            if (!empty($clientOptions)) {
232
                $this->form->attributes[] = $clientOptions;
233
            }
234
        }
235
236 16
        $inputID = $this->getInputId();
237 16
        $attribute = Html::getAttributeName($this->attribute);
238 16
        $options = $this->options;
239 16
        $class = isset($options['class']) ? (array) $options['class'] : [];
240 16
        $class[] = "field-$inputID";
241 16
        if ($this->model->isAttributeRequired($attribute)) {
242 3
            $class[] = $this->form->requiredCssClass;
243
        }
244 16
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_CONTAINER) {
245 15
            $this->addErrorClassIfNeeded($options);
246
        }
247 16
        $options['class'] = implode(' ', $class);
248 16
        $tag = ArrayHelper::remove($options, 'tag', 'div');
249
250 16
        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 13
    public function end()
258
    {
259 13
        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 14
    public function label($label = null, $options = [])
273
    {
274 14
        if ($label === false) {
275 4
            $this->parts['{label}'] = '';
276 4
            return $this;
277
        }
278
279 12
        $options = array_merge($this->labelOptions, $options);
280 12
        if ($label !== null) {
281 2
            $options['label'] = $label;
282
        }
283
284 12
        if ($this->_skipLabelFor) {
285
            $options['for'] = null;
286
        }
287
288 12
        $this->parts['{label}'] = Html::activeLabel($this->model, $this->attribute, $options);
289
290 12
        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 12
    public function error($options = [])
310
    {
311 12
        if ($options === false) {
312 2
            $this->parts['{error}'] = '';
313 2
            return $this;
314
        }
315 10
        $options = array_merge($this->errorOptions, $options);
316 10
        $this->parts['{error}'] = Html::error($this->model, $this->attribute, $options);
317
318 10
        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 15
    public function hint($content, $options = [])
338
    {
339 15
        if ($content === false) {
340 3
            $this->parts['{hint}'] = '';
341 3
            return $this;
342
        }
343
344 12
        $options = array_merge($this->hintOptions, $options);
345 12
        if ($content !== null) {
346 1
            $options['hint'] = $content;
347
        }
348 12
        $this->parts['{hint}'] = Html::activeHint($this->model, $this->attribute, $options);
349
350 12
        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
    public function radioList($items, $options = [])
726
    {
727
        if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
728
            $this->addErrorClassIfNeeded($options);
729
        }
730
731
        $this->addAriaAttributes($options);
732
        $this->adjustLabelFor($options);
733
        $this->_skipLabelFor = true;
734
        $this->parts['{input}'] = Html::activeRadioList($this->model, $this->attribute, $items, $options);
735
736
        return $this;
737
    }
738
739
    /**
740
     * Renders a widget as the input of the field.
741
     *
742
     * Note that the widget must have both `model` and `attribute` properties. They will
743
     * be initialized with [[model]] and [[attribute]] of this field, respectively.
744
     *
745
     * If you want to use a widget that does not have `model` and `attribute` properties,
746
     * please use [[render()]] instead.
747
     *
748
     * For example to use the [[MaskedInput]] widget to get some date input, you can use
749
     * the following code, assuming that `$form` is your [[ActiveForm]] instance:
750
     *
751
     * ```php
752
     * $form->field($model, 'date')->widget(\yii\widgets\MaskedInput::className(), [
753
     *     'mask' => '99/99/9999',
754
     * ]);
755
     * ```
756
     *
757
     * If you set a custom `id` for the input element, you may need to adjust the [[$selectors]] accordingly.
758
     *
759
     * @param string $class the widget class name.
760
     * @param array $config name-value pairs that will be used to initialize the widget.
761
     * @return $this the field object itself.
762
     */
763 1
    public function widget($class, $config = [])
764
    {
765
        /* @var $class \yii\base\Widget */
766 1
        $config['model'] = $this->model;
767 1
        $config['attribute'] = $this->attribute;
768 1
        $config['view'] = $this->form->getView();
769 1
        if (is_subclass_of($class, 'yii\widgets\InputWidget')) {
770 1
            $config['field'] = $this;
771 1
            if (isset($config['options'])) {
772 1
                if ($this->form->validationStateOn === ActiveForm::VALIDATION_STATE_ON_INPUT) {
773
                    $this->addErrorClassIfNeeded($options);
774
                }
775
776 1
                $this->addAriaAttributes($config['options']);
777 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...
778
            }
779
        }
780
781 1
        $this->parts['{input}'] = $class::widget($config);
782
783 1
        return $this;
784
    }
785
786
    /**
787
     * Adjusts the `for` attribute for the label based on the input options.
788
     * @param array $options the input options.
789
     */
790 19
    protected function adjustLabelFor($options)
791
    {
792 19
        if (!isset($options['id'])) {
793 16
            return;
794
        }
795 3
        $this->_inputId = $options['id'];
796 3
        if (!isset($this->labelOptions['for'])) {
797 3
            $this->labelOptions['for'] = $options['id'];
798
        }
799 3
    }
800
801
    /**
802
     * Returns the JS options for the field.
803
     * @return array the JS options.
804
     */
805 5
    protected function getClientOptions()
806
    {
807 5
        $attribute = Html::getAttributeName($this->attribute);
808 5
        if (!in_array($attribute, $this->model->activeAttributes(), true)) {
809 1
            return [];
810
        }
811
812 4
        $clientValidation = $this->isClientValidationEnabled();
813 4
        $ajaxValidation = $this->isAjaxValidationEnabled();
814
815 4
        if ($clientValidation) {
816 3
            $validators = [];
817 3
            foreach ($this->model->getActiveValidators($attribute) as $validator) {
818
                /* @var $validator \yii\validators\Validator */
819 3
                $js = $validator->clientValidateAttribute($this->model, $attribute, $this->form->getView());
820 3
                if ($validator->enableClientValidation && $js != '') {
821 3
                    if ($validator->whenClient !== null) {
822 1
                        $js = "if (({$validator->whenClient})(attribute, value)) { $js }";
823
                    }
824 3
                    $validators[] = $js;
825
                }
826
            }
827
        }
828
829 4
        if (!$ajaxValidation && (!$clientValidation || empty($validators))) {
830 1
            return [];
831
        }
832
833 3
        $options = [];
834
835 3
        $inputID = $this->getInputId();
836 3
        $options['id'] = Html::getInputId($this->model, $this->attribute);
837 3
        $options['name'] = $this->attribute;
838
839 3
        $options['container'] = isset($this->selectors['container']) ? $this->selectors['container'] : ".field-$inputID";
840 3
        $options['input'] = isset($this->selectors['input']) ? $this->selectors['input'] : "#$inputID";
841 3
        if (isset($this->selectors['error'])) {
842
            $options['error'] = $this->selectors['error'];
843 3
        } elseif (isset($this->errorOptions['class'])) {
844 3
            $options['error'] = '.' . implode('.', preg_split('/\s+/', $this->errorOptions['class'], -1, PREG_SPLIT_NO_EMPTY));
845
        } else {
846
            $options['error'] = isset($this->errorOptions['tag']) ? $this->errorOptions['tag'] : 'span';
847
        }
848
849 3
        $options['encodeError'] = !isset($this->errorOptions['encode']) || $this->errorOptions['encode'];
850 3
        if ($ajaxValidation) {
851 2
            $options['enableAjaxValidation'] = true;
852
        }
853 3
        foreach (['validateOnChange', 'validateOnBlur', 'validateOnType', 'validationDelay'] as $name) {
854 3
            $options[$name] = $this->$name === null ? $this->form->$name : $this->$name;
855
        }
856
857 3
        if (!empty($validators)) {
858 3
            $options['validate'] = new JsExpression('function (attribute, value, messages, deferred, $form) {' . implode('', $validators) . '}');
859
        }
860
861 3
        if ($this->addAriaAttributes === false) {
862
            $options['updateAriaInvalid'] = false;
863
        }
864
865
        // only get the options that are different from the default ones (set in yii.activeForm.js)
866 3
        return array_diff_assoc($options, [
867 3
            'validateOnChange' => true,
868
            'validateOnBlur' => true,
869
            'validateOnType' => false,
870
            'validationDelay' => 500,
871
            'encodeError' => true,
872
            'error' => '.help-block',
873
            'updateAriaInvalid' => true,
874
        ]);
875
    }
876
877
    /**
878
     * Checks if client validation enabled for the field.
879
     * @return bool
880
     * @since 2.0.11
881
     */
882 4
    protected function isClientValidationEnabled()
883
    {
884 4
        return $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation;
885
    }
886
887
    /**
888
     * Checks if ajax validation enabled for the field.
889
     * @return bool
890
     * @since 2.0.11
891
     */
892 4
    protected function isAjaxValidationEnabled()
893
    {
894 4
        return $this->enableAjaxValidation || $this->enableAjaxValidation === null && $this->form->enableAjaxValidation;
895
    }
896
897
    /**
898
     * Returns the HTML `id` of the input element of this form field.
899
     * @return string the input id.
900
     * @since 2.0.7
901
     */
902 19
    protected function getInputId()
903
    {
904 19
        return $this->_inputId ?: Html::getInputId($this->model, $this->attribute);
905
    }
906
907
    /**
908
     * Adds aria attributes to the input options.
909
     * @param $options array input options
910
     * @since 2.0.11
911
     */
912 16
    protected function addAriaAttributes(&$options)
913
    {
914 16
        if ($this->addAriaAttributes) {
915 16
            if (!isset($options['aria-required']) && $this->model->isAttributeRequired($this->attribute)) {
916 1
                $options['aria-required'] = 'true';
917
            }
918 16
            if (!isset($options['aria-invalid'])) {
919 16
                if ($this->model->hasErrors($this->attribute)) {
920 2
                    $options['aria-invalid'] = 'true';
921
                }
922
            }
923
        }
924 16
    }
925
926
    /**
927
     * Adds validation class to the input options if needed.
928
     * @param $options array input options
929
     * @since 2.0.14
930
     */
931 16
    protected function addErrorClassIfNeeded(&$options)
932
    {
933 16
        if ($this->model->hasErrors($this->attribute)) {
934 4
            Html::addCssClass($options, $this->form->errorCssClass);
935
        }
936 16
    }
937
}
938