Completed
Push — readme-redesign ( e2fd40...17eb05 )
by Alexander
108:51 queued 68:52
created

ActiveField::getClientOptions()   F

Complexity

Conditions 21
Paths 1539

Size

Total Lines 71
Code Lines 45

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 71
rs 2.5491
c 0
b 0
f 0
cc 21
eloc 45
nc 1539
nop 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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