Completed
Push — security-enhancements ( 371440 )
by Alexander
08:04
created

ActiveField::render()   C

Complexity

Conditions 7
Paths 18

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

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