Class yii\helpers\Html

Inheritanceyii\helpers\Html » yii\helpers\BaseHtml
Available since version2.0
Source Code https://github.com/yiisoft/yii2/blob/master/framework/helpers/Html.php

Html provides a set of static methods for generating commonly used HTML tags.

Nearly all of the methods in this class allow setting additional html attributes for the html tags they generate. You can specify, for example, class, style or id for an html element using the $options parameter. See the documentation of the tag() method for more details.

For more details and usage information on Html, see the guide article on html helpers.

Public Properties

Hide inherited properties

Property Type Description Defined By
$attributeOrder array The preferred order of attributes in a tag. yii\helpers\BaseHtml
$attributeRegex string Regular expression used for attribute name validation. yii\helpers\BaseHtml
$dataAttributes array List of tag attributes that should be specially handled when their values are of array type. yii\helpers\BaseHtml
$normalizeClassAttribute boolean Whether to removes duplicate class names in tag attribute class yii\helpers\BaseHtml
$voidElements array List of void elements (element name => 1) yii\helpers\BaseHtml

Public Methods

Hide inherited methods

Method Description Defined By
a() Generates a hyperlink tag. yii\helpers\BaseHtml
activeCheckbox() Generates a checkbox tag together with a label for the given model attribute. yii\helpers\BaseHtml
activeCheckboxList() Generates a list of checkboxes. yii\helpers\BaseHtml
activeDropDownList() Generates a drop-down list for the given model attribute. yii\helpers\BaseHtml
activeFileInput() Generates a file input tag for the given model attribute. yii\helpers\BaseHtml
activeHiddenInput() Generates a hidden input tag for the given model attribute. yii\helpers\BaseHtml
activeHint() Generates a hint tag for the given model attribute. yii\helpers\BaseHtml
activeInput() Generates an input tag for the given model attribute. yii\helpers\BaseHtml
activeLabel() Generates a label tag for the given model attribute. yii\helpers\BaseHtml
activeListBox() Generates a list box. yii\helpers\BaseHtml
activePasswordInput() Generates a password input tag for the given model attribute. yii\helpers\BaseHtml
activeRadio() Generates a radio button tag together with a label for the given model attribute. yii\helpers\BaseHtml
activeRadioList() Generates a list of radio buttons. yii\helpers\BaseHtml
activeTextInput() Generates a text input tag for the given model attribute. yii\helpers\BaseHtml
activeTextarea() Generates a textarea tag for the given model attribute. yii\helpers\BaseHtml
addCssClass() Adds a CSS class (or several classes) to the specified options. yii\helpers\BaseHtml
addCssStyle() Adds the specified CSS style to the HTML options. yii\helpers\BaseHtml
beginForm() Generates a form start tag. yii\helpers\BaseHtml
beginTag() Generates a start tag. yii\helpers\BaseHtml
button() Generates a button tag. yii\helpers\BaseHtml
buttonInput() Generates an input button. yii\helpers\BaseHtml
checkbox() Generates a checkbox input. yii\helpers\BaseHtml
checkboxList() Generates a list of checkboxes. yii\helpers\BaseHtml
csrfMetaTags() Generates the meta tags containing CSRF token information. yii\helpers\BaseHtml
cssFile() Generates a link tag that refers to an external CSS file. yii\helpers\BaseHtml
cssStyleFromArray() Converts a CSS style array into a string representation. yii\helpers\BaseHtml
cssStyleToArray() Converts a CSS style string into an array representation. yii\helpers\BaseHtml
decode() Decodes special HTML entities back to the corresponding characters. yii\helpers\BaseHtml
encode() Encodes special characters into HTML entities. yii\helpers\BaseHtml
endForm() Generates a form end tag. yii\helpers\BaseHtml
endTag() Generates an end tag. yii\helpers\BaseHtml
error() Generates a tag that contains the first validation error of the specified model attribute. yii\helpers\BaseHtml
errorSummary() Generates a summary of the validation errors. yii\helpers\BaseHtml
escapeJsRegularExpression() Escapes regular expression to use in JavaScript. yii\helpers\BaseHtml
fileInput() Generates a file input field. yii\helpers\BaseHtml
getAttributeName() Returns the real attribute name from the given attribute expression. yii\helpers\BaseHtml
getAttributeValue() Returns the value of the specified attribute name or expression. yii\helpers\BaseHtml
getInputId() Generates an appropriate input ID for the specified attribute name or expression. yii\helpers\BaseHtml
getInputIdByName() Converts input name to ID. yii\helpers\BaseHtml
getInputName() Generates an appropriate input name for the specified attribute name or expression. yii\helpers\BaseHtml
hiddenInput() Generates a hidden input field. yii\helpers\BaseHtml
img() Generates an image tag. yii\helpers\BaseHtml
input() Generates an input type of the given type. yii\helpers\BaseHtml
jsFile() Generates a script tag that refers to an external JavaScript file. yii\helpers\BaseHtml
label() Generates a label tag. yii\helpers\BaseHtml
listBox() Generates a list box. yii\helpers\BaseHtml
mailto() Generates a mailto hyperlink. yii\helpers\BaseHtml
ol() Generates an ordered list. yii\helpers\BaseHtml
passwordInput() Generates a password input field. yii\helpers\BaseHtml
radio() Generates a radio button input. yii\helpers\BaseHtml
radioList() Generates a list of radio buttons. yii\helpers\BaseHtml
removeCssClass() Removes a CSS class from the specified options. yii\helpers\BaseHtml
removeCssStyle() Removes the specified CSS style from the HTML options. yii\helpers\BaseHtml
renderSelectOptions() Renders the option tags that can be used by dropDownList() and listBox(). yii\helpers\BaseHtml
renderTagAttributes() Renders the HTML tag attributes. yii\helpers\BaseHtml
resetButton() Generates a reset button tag. yii\helpers\BaseHtml
resetInput() Generates a reset input button. yii\helpers\BaseHtml
script() Generates a script tag. yii\helpers\BaseHtml
style() Generates a style tag. yii\helpers\BaseHtml
submitButton() Generates a submit button tag. yii\helpers\BaseHtml
submitInput() Generates a submit input button. yii\helpers\BaseHtml
tag() Generates a complete HTML tag. yii\helpers\BaseHtml
textInput() Generates a text input field. yii\helpers\BaseHtml
textarea() Generates a text area input. yii\helpers\BaseHtml
ul() Generates an unordered list. yii\helpers\BaseHtml

Protected Methods

Hide inherited methods

Method Description Defined By
activeBooleanInput() Generates a boolean input This method is mainly called by activeCheckbox() and activeRadio(). yii\helpers\BaseHtml
activeListInput() Generates a list of input fields. yii\helpers\BaseHtml
booleanInput() Generates a boolean input. yii\helpers\BaseHtml
setActivePlaceholder() Generate placeholder from model attribute label. yii\helpers\BaseHtml

Method Details

Hide inherited methods

a() public static method

Defined in: yii\helpers\BaseHtml::a()

Generates a hyperlink tag.

See also yii\helpers\Url::to().

public static string a ( $text, $url null, $options = [] )
$text string

Link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is coming from end users, you should consider encode() it to prevent XSS attacks.

$url array|string|null

The URL for the hyperlink tag. This parameter will be processed by yii\helpers\Url::to() and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute will not be generated.

If you want to use an absolute url you can call yii\helpers\Url::to() yourself, before passing the URL to this method, like this:

Html::a('link text', Url::to($url, true))
$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated hyperlink

                public static function a($text, $url = null, $options = [])
{
    if ($url !== null) {
        $options['href'] = Url::to($url);
    }
    return static::tag('a', $text, $options);
}

            
activeBooleanInput() protected static method (available since version 2.0.9)

Defined in: yii\helpers\BaseHtml::activeBooleanInput()

Generates a boolean input This method is mainly called by activeCheckbox() and activeRadio().

protected static string activeBooleanInput ( $type, $model, $attribute, $options = [] )
$type string

The input type. This can be either radio or checkbox.

$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. See booleanInput() for details about accepted attributes.

return string

The generated input element

                protected static function activeBooleanInput($type, $model, $attribute, $options = [])
{
    $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
    $value = static::getAttributeValue($model, $attribute);
    if (!array_key_exists('value', $options)) {
        $options['value'] = '1';
    }
    if (!array_key_exists('uncheck', $options)) {
        $options['uncheck'] = '0';
    } elseif ($options['uncheck'] === false) {
        unset($options['uncheck']);
    }
    if (!array_key_exists('label', $options)) {
        $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
    } elseif ($options['label'] === false) {
        unset($options['label']);
    }
    $checked = "$value" === "{$options['value']}";
    if (!array_key_exists('id', $options)) {
        $options['id'] = static::getInputId($model, $attribute);
    }
    return static::$type($name, $checked, $options);
}

            
activeCheckbox() public static method

Defined in: yii\helpers\BaseHtml::activeCheckbox()

Generates a checkbox tag together with a label for the given model attribute.

This method will generate the "checked" tag attribute according to the model attribute value.

public static string activeCheckbox ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. See booleanInput() for details about accepted attributes.

return string

The generated checkbox tag

                public static function activeCheckbox($model, $attribute, $options = [])
{
    return static::activeBooleanInput('checkbox', $model, $attribute, $options);
}

            
activeCheckboxList() public static method

Defined in: yii\helpers\BaseHtml::activeCheckboxList()

Generates a list of checkboxes.

A checkbox list allows multiple selection, like listBox(). As a result, the corresponding submitted value is an array. The selection of the checkbox list is taken from the value of the model attribute.

public static string activeCheckboxList ( $model, $attribute, $items, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$items array

The data item used to generate the checkboxes. The array keys are the checkbox values, and the array values are the corresponding labels.

$options array

Options (name => config) for the checkbox list container tag. The following options are specially handled:

  • tag: string|false, the tag name of the container element. False to render checkbox without container. See also tag().
  • unselect: string, the value that should be submitted when none of the checkboxes is selected. You may set this option to be null to prevent default value submission. If this option is not set, an empty string will be submitted.
  • encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. This option is ignored if item option is set.
  • separator: string, the HTML code that separates items.
  • itemOptions: array, the options for generating the checkbox tag using checkbox().
  • item: callable, a callback that can be used to customize the generation of the HTML code corresponding to a single item in $items. The signature of this callback must be:

    function ($index, $label, $name, $checked, $value)
    

    where $index is the zero-based index of the checkbox in the whole list; $label is the label for the checkbox; and $name, $value and $checked represent the name, value and the checked status of the checkbox input.

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated checkbox list

                public static function activeCheckboxList($model, $attribute, $items, $options = [])
{
    return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
}

            
activeDropDownList() public static method

Defined in: yii\helpers\BaseHtml::activeDropDownList()

Generates a drop-down list for the given model attribute.

The selection of the drop-down list is taken from the value of the model attribute.

public static string activeDropDownList ( $model, $attribute, $items, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$items array

The option data items. The array keys are option values, and the array values are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). For each sub-array, an option group will be generated whose label is the key associated with the sub-array. If you have a list of data models, you may convert them into the format described above using yii\helpers\ArrayHelper::map().

Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in the labels will also be HTML-encoded.

$options array

The tag options in terms of name-value pairs. The following options are specially handled:

  • prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array to override the value and to set other tag attributes:

    ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
    
  • options: array, the attributes for the select option tags. The array keys must be valid option values, and the array values are the extra attributes for the corresponding option tags. For example,

    [
        'value1' => ['disabled' => true],
        'value2' => ['label' => 'value 2'],
    ];
    
  • groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', except that the array keys represent the optgroup labels specified in $items.
  • encodeSpaces: bool, whether to encode spaces in option prompt and option value with   character. Defaults to false.
  • encode: bool, whether to encode option prompt and option value characters. Defaults to true. This option is available since 2.0.3.

The rest of the options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated drop-down list tag

                public static function activeDropDownList($model, $attribute, $items, $options = [])
{
    if (empty($options['multiple'])) {
        return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
    }
    return static::activeListBox($model, $attribute, $items, $options);
}

            
activeFileInput() public static method

Defined in: yii\helpers\BaseHtml::activeFileInput()

Generates a file input tag for the given model attribute.

This method will generate the "name" and "value" tag attributes automatically for the model attribute unless they are explicitly specified in $options. Additionally, if a separate set of HTML options array is defined inside $options with a key named hiddenOptions, it will be passed to the activeHiddenInput field as its own $options parameter.

public static string activeFileInput ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). See renderTagAttributes() for details on how attributes are being rendered. If hiddenOptions parameter which is another set of HTML options array is defined, it will be extracted from $options to be used for the hidden input.

return string

The generated input tag

                public static function activeFileInput($model, $attribute, $options = [])
{
    $hiddenOptions = ['id' => null, 'value' => ''];
    if (isset($options['name'])) {
        $hiddenOptions['name'] = $options['name'];
    }
    // make sure disabled input is not sending any value
    if (!empty($options['disabled'])) {
        $hiddenOptions['disabled'] = $options['disabled'];
    }
    $hiddenOptions = ArrayHelper::merge($hiddenOptions, ArrayHelper::remove($options, 'hiddenOptions', []));
    // Add a hidden field so that if a model only has a file field, we can
    // still use isset($_POST[$modelClass]) to detect if the input is submitted.
    // The hidden input will be assigned its own set of html options via `$hiddenOptions`.
    // This provides the possibility to interact with the hidden field via client script.
    // Note: For file-field-only model with `disabled` option set to `true` input submitting detection won't work.
    return static::activeHiddenInput($model, $attribute, $hiddenOptions)
        . static::activeInput('file', $model, $attribute, $options);
}

            
activeHiddenInput() public static method

Defined in: yii\helpers\BaseHtml::activeHiddenInput()

Generates a hidden input tag for the given model attribute.

This method will generate the "name" and "value" tag attributes automatically for the model attribute unless they are explicitly specified in $options.

public static string activeHiddenInput ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated input tag

                public static function activeHiddenInput($model, $attribute, $options = [])
{
    return static::activeInput('hidden', $model, $attribute, $options);
}

            
activeHint() public static method (available since version 2.0.4)

Defined in: yii\helpers\BaseHtml::activeHint()

Generates a hint tag for the given model attribute.

The hint text is the hint associated with the attribute, obtained via yii\base\Model::getAttributeHint(). If no hint content can be obtained, method will return an empty string.

public static string activeHint ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. The following options are specially handled:

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated hint tag

                public static function activeHint($model, $attribute, $options = [])
{
    $attribute = static::getAttributeName($attribute);
    $hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute);
    if (empty($hint)) {
        return '';
    }
    $tag = ArrayHelper::remove($options, 'tag', 'div');
    unset($options['hint']);
    return static::tag($tag, $hint, $options);
}

            
activeInput() public static method

Defined in: yii\helpers\BaseHtml::activeInput()

Generates an input tag for the given model attribute.

This method will generate the "name" and "value" tag attributes automatically for the model attribute unless they are explicitly specified in $options.

public static string activeInput ( $type, $model, $attribute, $options = [] )
$type string

The input type (e.g. 'text', 'password')

$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated input tag

                public static function activeInput($type, $model, $attribute, $options = [])
{
    $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
    $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
    if (!array_key_exists('id', $options)) {
        $options['id'] = static::getInputId($model, $attribute);
    }
    static::setActivePlaceholder($model, $attribute, $options);
    self::normalizeMaxLength($model, $attribute, $options);
    return static::input($type, $name, $value, $options);
}

            
activeLabel() public static method

Defined in: yii\helpers\BaseHtml::activeLabel()

Generates a label tag for the given model attribute.

The label text is the label associated with the attribute, obtained via yii\base\Model::getAttributeLabel().

public static string activeLabel ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. The following options are specially handled:

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated label tag

                public static function activeLabel($model, $attribute, $options = [])
{
    $for = ArrayHelper::remove($options, 'for', static::getInputId($model, $attribute));
    $attribute = static::getAttributeName($attribute);
    $label = ArrayHelper::remove($options, 'label', static::encode($model->getAttributeLabel($attribute)));
    return static::label($label, $for, $options);
}

            
activeListBox() public static method

Defined in: yii\helpers\BaseHtml::activeListBox()

Generates a list box.

The selection of the list box is taken from the value of the model attribute.

public static string activeListBox ( $model, $attribute, $items, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$items array

The option data items. The array keys are option values, and the array values are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). For each sub-array, an option group will be generated whose label is the key associated with the sub-array. If you have a list of data models, you may convert them into the format described above using yii\helpers\ArrayHelper::map().

Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in the labels will also be HTML-encoded.

$options array

The tag options in terms of name-value pairs. The following options are specially handled:

  • prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array to override the value and to set other tag attributes:

    ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
    
  • options: array, the attributes for the select option tags. The array keys must be valid option values, and the array values are the extra attributes for the corresponding option tags. For example,

    [
        'value1' => ['disabled' => true],
        'value2' => ['label' => 'value 2'],
    ];
    
  • groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', except that the array keys represent the optgroup labels specified in $items.
  • unselect: string, the value that will be submitted when no option is selected. When this attribute is set, a hidden field will be generated so that if no option is selected in multiple mode, we can still obtain the posted unselect value.
  • encodeSpaces: bool, whether to encode spaces in option prompt and option value with   character. Defaults to false.
  • encode: bool, whether to encode option prompt and option value characters. Defaults to true. This option is available since 2.0.3.

The rest of the options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated list box tag

                public static function activeListBox($model, $attribute, $items, $options = [])
{
    return static::activeListInput('listBox', $model, $attribute, $items, $options);
}

            
activeListInput() protected static method

Defined in: yii\helpers\BaseHtml::activeListInput()

Generates a list of input fields.

This method is mainly called by activeListBox(), activeRadioList() and activeCheckboxList().

protected static string activeListInput ( $type, $model, $attribute, $items, $options = [] )
$type string

The input type. This can be 'listBox', 'radioList', or 'checkBoxList'.

$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$items array

The data item used to generate the input fields. The array keys are the input values, and the array values are the corresponding labels.

$options array

Options (name => config) for the input list. The supported special options depend on the input type specified by $type.

return string

The generated input list

                protected static function activeListInput($type, $model, $attribute, $items, $options = [])
{
    $name = ArrayHelper::remove($options, 'name', static::getInputName($model, $attribute));
    $selection = ArrayHelper::remove($options, 'value', static::getAttributeValue($model, $attribute));
    if (!array_key_exists('unselect', $options)) {
        $options['unselect'] = '';
    }
    if (!array_key_exists('id', $options)) {
        $options['id'] = static::getInputId($model, $attribute);
    }
    return static::$type($name, $selection, $items, $options);
}

            
activePasswordInput() public static method

Defined in: yii\helpers\BaseHtml::activePasswordInput()

Generates a password input tag for the given model attribute.

This method will generate the "name" and "value" tag attributes automatically for the model attribute unless they are explicitly specified in $options.

public static string activePasswordInput ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). See renderTagAttributes() for details on how attributes are being rendered. The following special options are recognized:

  • maxlength: integer|boolean, when maxlength is set true and the model attribute is validated by a string validator, the maxlength option will take the max value of yii\validators\StringValidator::$max and [[\yii\validators\StringValidator::length]. This is available since version 2.0.6 and improved taking length into account since version 2.0.42.
  • placeholder: string|boolean, when placeholder equals true, the attribute label from the $model will be used as a placeholder (this behavior is available since version 2.0.14).
return string

The generated input tag

                public static function activePasswordInput($model, $attribute, $options = [])
{
    return static::activeInput('password', $model, $attribute, $options);
}

            
activeRadio() public static method

Defined in: yii\helpers\BaseHtml::activeRadio()

Generates a radio button tag together with a label for the given model attribute.

This method will generate the "checked" tag attribute according to the model attribute value.

public static string activeRadio ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. See booleanInput() for details about accepted attributes.

return string

The generated radio button tag

                public static function activeRadio($model, $attribute, $options = [])
{
    return static::activeBooleanInput('radio', $model, $attribute, $options);
}

            
activeRadioList() public static method

Defined in: yii\helpers\BaseHtml::activeRadioList()

Generates a list of radio buttons.

A radio button list is like a checkbox list, except that it only allows single selection. The selection of the radio buttons is taken from the value of the model attribute.

public static string activeRadioList ( $model, $attribute, $items, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$items array

The data item used to generate the radio buttons. The array keys are the radio values, and the array values are the corresponding labels.

$options array

Options (name => config) for the radio button list container tag. The following options are specially handled:

  • tag: string|false, the tag name of the container element. False to render radio button without container. See also tag().
  • unselect: string, the value that should be submitted when none of the radio buttons is selected. You may set this option to be null to prevent default value submission. If this option is not set, an empty string will be submitted.
  • encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. This option is ignored if item option is set.
  • separator: string, the HTML code that separates items.
  • itemOptions: array, the options for generating the radio button tag using radio().
  • item: callable, a callback that can be used to customize the generation of the HTML code corresponding to a single item in $items. The signature of this callback must be:

    function ($index, $label, $name, $checked, $value)
    

    where $index is the zero-based index of the radio button in the whole list; $label is the label for the radio button; and $name, $value and $checked represent the name, value and the checked status of the radio button input.

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated radio button list

                public static function activeRadioList($model, $attribute, $items, $options = [])
{
    return static::activeListInput('radioList', $model, $attribute, $items, $options);
}

            
activeTextInput() public static method

Defined in: yii\helpers\BaseHtml::activeTextInput()

Generates a text input tag for the given model attribute.

This method will generate the "name" and "value" tag attributes automatically for the model attribute unless they are explicitly specified in $options.

public static string activeTextInput ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). See renderTagAttributes() for details on how attributes are being rendered. The following special options are recognized:

  • maxlength: integer|boolean, when maxlength is set true and the model attribute is validated by a string validator, the maxlength option will take the max value of yii\validators\StringValidator::$max and [[\yii\validators\StringValidator::length]. This is available since version 2.0.3 and improved taking length into account since version 2.0.42.
  • placeholder: string|boolean, when placeholder equals true, the attribute label from the $model will be used as a placeholder (this behavior is available since version 2.0.14).
return string

The generated input tag

                public static function activeTextInput($model, $attribute, $options = [])
{
    return static::activeInput('text', $model, $attribute, $options);
}

            
activeTextarea() public static method

Defined in: yii\helpers\BaseHtml::activeTextarea()

Generates a textarea tag for the given model attribute.

The model attribute value will be used as the content in the textarea.

public static string activeTextarea ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). See renderTagAttributes() for details on how attributes are being rendered. The following special options are recognized:

  • maxlength: integer|boolean, when maxlength is set true and the model attribute is validated by a string validator, the maxlength option will take the max value of yii\validators\StringValidator::$max and [[\yii\validators\StringValidator::length]. This is available since version 2.0.6 and improved taking length into account since version 2.0.42.
  • placeholder: string|boolean, when placeholder equals true, the attribute label from the $model will be used as a placeholder (this behavior is available since version 2.0.14).
return string

The generated textarea tag

                public static function activeTextarea($model, $attribute, $options = [])
{
    $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
    if (isset($options['value'])) {
        $value = $options['value'];
        unset($options['value']);
    } else {
        $value = static::getAttributeValue($model, $attribute);
    }
    if (!array_key_exists('id', $options)) {
        $options['id'] = static::getInputId($model, $attribute);
    }
    self::normalizeMaxLength($model, $attribute, $options);
    static::setActivePlaceholder($model, $attribute, $options);
    return static::textarea($name, $value, $options);
}

            
addCssClass() public static method

Defined in: yii\helpers\BaseHtml::addCssClass()

Adds a CSS class (or several classes) to the specified options.

If the CSS class is already in the options, it will not be added again. If class specification at given options is an array, and some class placed there with the named (string) key, overriding of such key will have no effect. For example:

$options = ['class' => ['persistent' => 'initial']];
Html::addCssClass($options, ['persistent' => 'override']);
var_dump($options['class']); // outputs: array('persistent' => 'initial');

See also removeCssClass().

public static void addCssClass ( &$options, $class )
$options array

The options to be modified.

$class string|array

The CSS class(es) to be added

                public static function addCssClass(&$options, $class)
{
    if (isset($options['class'])) {
        if (is_array($options['class'])) {
            $options['class'] = self::mergeCssClasses($options['class'], (array) $class);
        } else {
            $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
            $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
        }
    } else {
        $options['class'] = $class;
    }
}

            
addCssStyle() public static method

Defined in: yii\helpers\BaseHtml::addCssStyle()

Adds the specified CSS style to the HTML options.

If the options already contain a style element, the new style will be merged with the existing one. If a CSS property exists in both the new and the old styles, the old one may be overwritten if $overwrite is true.

For example,

Html::addCssStyle($options, 'width: 100px; height: 200px');

See also:

public static void addCssStyle ( &$options, $style, $overwrite true )
$options array

The HTML options to be modified.

$style string|array

The new style string (e.g. 'width: 100px; height: 200px') or array (e.g. ['width' => '100px', 'height' => '200px']).

$overwrite boolean

Whether to overwrite existing CSS properties if the new style contain them too.

                public static function addCssStyle(&$options, $style, $overwrite = true)
{
    if (!empty($options['style'])) {
        $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
        $newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
        if (!$overwrite) {
            foreach ($newStyle as $property => $value) {
                if (isset($oldStyle[$property])) {
                    unset($newStyle[$property]);
                }
            }
        }
        $style = array_merge($oldStyle, $newStyle);
    }
    $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
}

            
beginForm() public static method

Defined in: yii\helpers\BaseHtml::beginForm()

Generates a form start tag.

See also endForm().

public static string beginForm ( $action '', $method 'post', $options = [] )
$action array|string

The form action URL. This parameter will be processed by yii\helpers\Url::to().

$method string

The form submission method, such as "post", "get", "put", "delete" (case-insensitive). Since most browsers only support "post" and "get", if other methods are given, they will be simulated using "post", and a hidden input will be added which contains the actual method type. See yii\web\Request::$methodParam for more details.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

Special options:

  • csrf: whether to generate the CSRF hidden input. Defaults to true.
return string

The generated form start tag.

                public static function beginForm($action = '', $method = 'post', $options = [])
{
    $action = Url::to($action);
    $hiddenInputs = [];
    $request = Yii::$app->getRequest();
    if ($request instanceof Request) {
        if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) {
            // simulate PUT, DELETE, etc. via POST
            $hiddenInputs[] = static::hiddenInput($request->methodParam, $method);
            $method = 'post';
        }
        $csrf = ArrayHelper::remove($options, 'csrf', true);
        if ($csrf && $request->enableCsrfValidation && strcasecmp($method, 'post') === 0) {
            $hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken());
        }
    }
    if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) {
        // query parameters in the action are ignored for GET method
        // we use hidden fields to add them back
        foreach (explode('&', substr($action, $pos + 1)) as $pair) {
            if (($pos1 = strpos($pair, '=')) !== false) {
                $hiddenInputs[] = static::hiddenInput(
                    urldecode(substr($pair, 0, $pos1)),
                    urldecode(substr($pair, $pos1 + 1))
                );
            } else {
                $hiddenInputs[] = static::hiddenInput(urldecode($pair), '');
            }
        }
        $action = substr($action, 0, $pos);
    }
    $options['action'] = $action;
    $options['method'] = $method;
    $form = static::beginTag('form', $options);
    if (!empty($hiddenInputs)) {
        $form .= "\n" . implode("\n", $hiddenInputs);
    }
    return $form;
}

            
beginTag() public static method

Defined in: yii\helpers\BaseHtml::beginTag()

Generates a start tag.

See also:

public static string beginTag ( $name, $options = [] )
$name string|boolean|null

The tag name. If $name is null or false, the corresponding content will be rendered without any tag.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated start tag

                public static function beginTag($name, $options = [])
{
    if ($name === null || $name === false) {
        return '';
    }
    return "<$name" . static::renderTagAttributes($options) . '>';
}

            
booleanInput() protected static method (available since version 2.0.9)

Defined in: yii\helpers\BaseHtml::booleanInput()

Generates a boolean input.

protected static string booleanInput ( $type, $name, $checked false, $options = [] )
$type string

The input type. This can be either radio or checkbox.

$name string

The name attribute.

$checked boolean

Whether the checkbox should be checked.

$options array

The tag options in terms of name-value pairs. The following options are specially handled:

  • uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute is present, a hidden input will be generated so that if the checkbox is not checked and is submitted, the value of this attribute will still be submitted to the server via the hidden input.
  • label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, you should encode() it to prevent XSS attacks. When this option is specified, the checkbox will be enclosed by a label tag.
  • labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option.

The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated checkbox tag

                protected static function booleanInput($type, $name, $checked = false, $options = [])
{
    // 'checked' option has priority over $checked argument
    if (!isset($options['checked'])) {
        $options['checked'] = (bool) $checked;
    }
    $value = array_key_exists('value', $options) ? $options['value'] : '1';
    if (isset($options['uncheck'])) {
        // add a hidden field so that if the checkbox is not selected, it still submits a value
        $hiddenOptions = [];
        if (isset($options['form'])) {
            $hiddenOptions['form'] = $options['form'];
        }
        // make sure disabled input is not sending any value
        if (!empty($options['disabled'])) {
            $hiddenOptions['disabled'] = $options['disabled'];
        }
        $hidden = static::hiddenInput($name, $options['uncheck'], $hiddenOptions);
        unset($options['uncheck']);
    } else {
        $hidden = '';
    }
    if (isset($options['label'])) {
        $label = $options['label'];
        $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
        unset($options['label'], $options['labelOptions']);
        $content = static::label(static::input($type, $name, $value, $options) . ' ' . $label, null, $labelOptions);
        return $hidden . $content;
    }
    return $hidden . static::input($type, $name, $value, $options);
}

            
button() public static method

Defined in: yii\helpers\BaseHtml::button()

Generates a button tag.

public static string button ( $content 'Button', $options = [] )
$content string

The content enclosed within the button tag. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, you should consider encode() it to prevent XSS attacks.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated button tag

                public static function button($content = 'Button', $options = [])
{
    if (!isset($options['type'])) {
        $options['type'] = 'button';
    }
    return static::tag('button', $content, $options);
}

            
buttonInput() public static method

Defined in: yii\helpers\BaseHtml::buttonInput()

Generates an input button.

public static string buttonInput ( $label 'Button', $options = [] )
$label string|null

The value attribute. If it is null, the value attribute will not be generated.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated button tag

                public static function buttonInput($label = 'Button', $options = [])
{
    $options['type'] = 'button';
    $options['value'] = $label;
    return static::tag('input', '', $options);
}

            
checkbox() public static method

Defined in: yii\helpers\BaseHtml::checkbox()

Generates a checkbox input.

public static string checkbox ( $name, $checked false, $options = [] )
$name string

The name attribute.

$checked boolean

Whether the checkbox should be checked.

$options array

The tag options in terms of name-value pairs. See booleanInput() for details about accepted attributes.

return string

The generated checkbox tag

                public static function checkbox($name, $checked = false, $options = [])
{
    return static::booleanInput('checkbox', $name, $checked, $options);
}

            
checkboxList() public static method

Defined in: yii\helpers\BaseHtml::checkboxList()

Generates a list of checkboxes.

A checkbox list allows multiple selection, like listBox(). As a result, the corresponding submitted value is an array.

public static string checkboxList ( $name, $selection null, $items = [], $options = [] )
$name string

The name attribute of each checkbox.

$selection string|array|null

The selected value(s). String for single or array for multiple selection(s).

$items array

The data item used to generate the checkboxes. The array keys are the checkbox values, while the array values are the corresponding labels.

$options array

Options (name => config) for the checkbox list container tag. The following options are specially handled:

  • tag: string|false, the tag name of the container element. False to render checkbox without container. See also tag().
  • unselect: string, the value that should be submitted when none of the checkboxes is selected. By setting this option, a hidden input will be generated.
  • disabled: boolean, whether the generated by unselect option hidden input should be disabled. Defaults to false. This option is available since version 2.0.16.
  • encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. This option is ignored if item option is set.
  • strict: boolean, if $selection is an array and this value is true a strict comparison will be performed on $items keys. Defaults to false. This option is available since 2.0.37.
  • separator: string, the HTML code that separates items.
  • itemOptions: array, the options for generating the checkbox tag using checkbox().
  • item: callable, a callback that can be used to customize the generation of the HTML code corresponding to a single item in $items. The signature of this callback must be:

    function ($index, $label, $name, $checked, $value)
    

    where $index is the zero-based index of the checkbox in the whole list; $label is the label for the checkbox; and $name, $value and $checked represent the name, value and the checked status of the checkbox input, respectively.

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated checkbox list

                public static function checkboxList($name, $selection = null, $items = [], $options = [])
{
    if (substr($name, -2) !== '[]') {
        $name .= '[]';
    }
    if (ArrayHelper::isTraversable($selection)) {
        $selection = array_map('strval', ArrayHelper::toArray($selection));
    }
    $formatter = ArrayHelper::remove($options, 'item');
    $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
    $encode = ArrayHelper::remove($options, 'encode', true);
    $separator = ArrayHelper::remove($options, 'separator', "\n");
    $tag = ArrayHelper::remove($options, 'tag', 'div');
    $strict = ArrayHelper::remove($options, 'strict', false);
    $lines = [];
    $index = 0;
    foreach ($items as $value => $label) {
        $checked = $selection !== null &&
            (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
                || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, $selection, $strict));
        if ($formatter !== null) {
            $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
        } else {
            $lines[] = static::checkbox($name, $checked, array_merge([
                'value' => $value,
                'label' => $encode ? static::encode($label) : $label,
            ], $itemOptions));
        }
        $index++;
    }
    if (isset($options['unselect'])) {
        // add a hidden field so that if the list box has no option being selected, it still submits a value
        $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
        $hiddenOptions = [];
        // make sure disabled input is not sending any value
        if (!empty($options['disabled'])) {
            $hiddenOptions['disabled'] = $options['disabled'];
        }
        $hidden = static::hiddenInput($name2, $options['unselect'], $hiddenOptions);
        unset($options['unselect'], $options['disabled']);
    } else {
        $hidden = '';
    }
    $visibleContent = implode($separator, $lines);
    if ($tag === false) {
        return $hidden . $visibleContent;
    }
    return $hidden . static::tag($tag, $visibleContent, $options);
}

            
csrfMetaTags() public static method

Defined in: yii\helpers\BaseHtml::csrfMetaTags()

Generates the meta tags containing CSRF token information.

See also yii\web\Request::$enableCsrfValidation.

public static string csrfMetaTags ( )
return string

The generated meta tags

                public static function csrfMetaTags()
{
    $request = Yii::$app->getRequest();
    if ($request instanceof Request && $request->enableCsrfValidation) {
        return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n"
            . static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n";
    }
    return '';
}

            
cssFile() public static method

Defined in: yii\helpers\BaseHtml::cssFile()

Generates a link tag that refers to an external CSS file.

See also yii\helpers\Url::to().

public static string cssFile ( $url, $options = [] )
$url array|string

The URL of the external CSS file. This parameter will be processed by yii\helpers\Url::to().

$options array

The tag options in terms of name-value pairs. The following options are specially handled:

  • condition: specifies the conditional comments for IE, e.g., lt IE 9. When this is specified, the generated link tag will be enclosed within the conditional comments. This is mainly useful for supporting old versions of IE browsers.
  • noscript: if set to true, link tag will be wrapped into <noscript> tags.

The rest of the options will be rendered as the attributes of the resulting link tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated link tag

                public static function cssFile($url, $options = [])
{
    if (!isset($options['rel'])) {
        $options['rel'] = 'stylesheet';
    }
    $options['href'] = Url::to($url);
    if (isset($options['condition'])) {
        $condition = $options['condition'];
        unset($options['condition']);
        return self::wrapIntoCondition(static::tag('link', '', $options), $condition);
    } elseif (isset($options['noscript']) && $options['noscript'] === true) {
        unset($options['noscript']);
        return '<noscript>' . static::tag('link', '', $options) . '</noscript>';
    }
    return static::tag('link', '', $options);
}

            
cssStyleFromArray() public static method

Defined in: yii\helpers\BaseHtml::cssStyleFromArray()

Converts a CSS style array into a string representation.

For example,

print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
// will display: 'width: 100px; height: 200px;'
public static string cssStyleFromArray ( array $style )
$style array

The CSS style array. The array keys are the CSS property names, and the array values are the corresponding CSS property values.

return string

The CSS style string. If the CSS style is empty, a null will be returned.

                public static function cssStyleFromArray(array $style)
{
    $result = '';
    foreach ($style as $name => $value) {
        $result .= "$name: $value; ";
    }
    // return null if empty to avoid rendering the "style" attribute
    return $result === '' ? null : rtrim($result);
}

            
cssStyleToArray() public static method

Defined in: yii\helpers\BaseHtml::cssStyleToArray()

Converts a CSS style string into an array representation.

The array keys are the CSS property names, and the array values are the corresponding CSS property values.

For example,

print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
// will display: ['width' => '100px', 'height' => '200px']
public static array cssStyleToArray ( $style )
$style string

The CSS style string

return array

The array representation of the CSS style

                public static function cssStyleToArray($style)
{
    $result = [];
    foreach (explode(';', $style) as $property) {
        $property = explode(':', $property);
        if (count($property) > 1) {
            $result[trim($property[0])] = trim($property[1]);
        }
    }
    return $result;
}

            
decode() public static method

Defined in: yii\helpers\BaseHtml::decode()

Decodes special HTML entities back to the corresponding characters.

This is the opposite of encode().

See also:

public static string decode ( $content )
$content string

The content to be decoded

return string

The decoded content

                public static function decode($content)
{
    return htmlspecialchars_decode($content, ENT_QUOTES);
}

            
encode() public static method

Defined in: yii\helpers\BaseHtml::encode()

Encodes special characters into HTML entities.

The application charset will be used for encoding.

See also:

public static string encode ( $content, $doubleEncode true )
$content string

The content to be encoded

$doubleEncode boolean

Whether to encode HTML entities in $content. If false, HTML entities in $content will not be further encoded.

return string

The encoded content

                public static function encode($content, $doubleEncode = true)
{
    return htmlspecialchars((string)$content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode);
}

            
endForm() public static method

Defined in: yii\helpers\BaseHtml::endForm()

Generates a form end tag.

See also beginForm().

public static string endForm ( )
return string

The generated tag

                public static function endForm()
{
    return '</form>';
}

            
endTag() public static method

Defined in: yii\helpers\BaseHtml::endTag()

Generates an end tag.

See also:

public static string endTag ( $name )
$name string|boolean|null

The tag name. If $name is null or false, the corresponding content will be rendered without any tag.

return string

The generated end tag

                public static function endTag($name)
{
    if ($name === null || $name === false) {
        return '';
    }
    return "</$name>";
}

            
error() public static method

Defined in: yii\helpers\BaseHtml::error()

Generates a tag that contains the first validation error of the specified model attribute.

Note that even if there is no validation error, this method will still return an empty error tag.

public static string error ( $model, $attribute, $options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered.

The following options are specially handled:

  • tag: this specifies the tag name. If not set, "div" will be used. See also tag().
  • encode: boolean, if set to false then the error message won't be encoded.
  • errorSource (since 2.0.14): \Closure|callable, callback that will be called to obtain an error message. The signature of the callback must be: function ($model, $attribute) and return a string. When not set, the $model->getFirstError() method will be called.

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated label tag

                public static function error($model, $attribute, $options = [])
{
    $attribute = static::getAttributeName($attribute);
    $errorSource = ArrayHelper::remove($options, 'errorSource');
    if ($errorSource !== null) {
        $error = call_user_func($errorSource, $model, $attribute);
    } else {
        $error = $model->getFirstError($attribute);
    }
    $tag = ArrayHelper::remove($options, 'tag', 'div');
    $encode = ArrayHelper::remove($options, 'encode', true);
    return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
}

            
errorSummary() public static method

Defined in: yii\helpers\BaseHtml::errorSummary()

Generates a summary of the validation errors.

If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.

public static string errorSummary ( $models, $options = [] )
$models yii\base\Model|yii\base\Model[]

The model(s) whose validation errors are to be displayed.

$options array

The tag options in terms of name-value pairs. The following options are specially handled:

  • header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
  • footer: string, the footer HTML for the error summary. Defaults to empty string.
  • encode: boolean, if set to false then the error messages won't be encoded. Defaults to true.
  • showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise only the first error message for each attribute will be shown. Defaults to false. Option is available since 2.0.10.

The rest of the options will be rendered as the attributes of the container tag.

return string

The generated error summary

                public static function errorSummary($models, $options = [])
{
    $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
    $footer = ArrayHelper::remove($options, 'footer', '');
    $encode = ArrayHelper::remove($options, 'encode', true);
    $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
    unset($options['header']);
    $lines = self::collectErrors($models, $encode, $showAllErrors);
    if (empty($lines)) {
        // still render the placeholder for client-side validation use
        $content = '<ul></ul>';
        $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
    } else {
        $content = '<ul><li>' . implode("</li>\n<li>", $lines) . '</li></ul>';
    }
    return Html::tag('div', $header . $content . $footer, $options);
}

            
escapeJsRegularExpression() public static method (available since version 2.0.6)

Defined in: yii\helpers\BaseHtml::escapeJsRegularExpression()

Escapes regular expression to use in JavaScript.

public static string escapeJsRegularExpression ( $regexp )
$regexp string

The regular expression to be escaped.

return string

The escaped result.

                public static function escapeJsRegularExpression($regexp)
{
    $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
    $deliminator = substr($pattern, 0, 1);
    $pos = strrpos($pattern, $deliminator, 1);
    $flag = substr($pattern, $pos + 1);
    if ($deliminator !== '/') {
        $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
    } else {
        $pattern = substr($pattern, 0, $pos + 1);
    }
    if (!empty($flag)) {
        $pattern .= preg_replace('/[^igmu]/', '', $flag);
    }
    return $pattern;
}

            
fileInput() public static method

Defined in: yii\helpers\BaseHtml::fileInput()

Generates a file input field.

To use a file input field, you should set the enclosing form's "enctype" attribute to be "multipart/form-data". After the form is submitted, the uploaded file information can be obtained via $_FILES[$name] (see PHP documentation).

public static string fileInput ( $name, $value null, $options = [] )
$name string

The name attribute.

$value string|null

The value attribute. If it is null, the value attribute will not be generated.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated file input tag

                public static function fileInput($name, $value = null, $options = [])
{
    return static::input('file', $name, $value, $options);
}

            
getAttributeName() public static method

Defined in: yii\helpers\BaseHtml::getAttributeName()

Returns the real attribute name from the given attribute expression.

An attribute expression is an attribute name prefixed and/or suffixed with array indexes. It is mainly used in tabular data input and/or input of array type. Below are some examples:

  • [0]content is used in tabular data input to represent the "content" attribute for the first model in tabular input;
  • dates[0] represents the first array element of the "dates" attribute;
  • [0]dates[0] represents the first array element of the "dates" attribute for the first model in tabular input.

If $attribute has neither prefix nor suffix, it will be returned back without change.

public static string getAttributeName ( $attribute )
$attribute string

The attribute name or expression

return string

The attribute name without prefix and suffix.

throws yii\base\InvalidArgumentException

if the attribute name contains non-word characters.

                public static function getAttributeName($attribute)
{
    if (preg_match(static::$attributeRegex, $attribute, $matches)) {
        return $matches[2];
    }
    throw new InvalidArgumentException('Attribute name must contain word characters only.');
}

            
getAttributeValue() public static method

Defined in: yii\helpers\BaseHtml::getAttributeValue()

Returns the value of the specified attribute name or expression.

For an attribute expression like [0]dates[0], this method will return the value of $model->dates[0]. See getAttributeName() for more details about attribute expression.

If an attribute value is an instance of yii\db\ActiveRecordInterface or an array of such instances, the primary value(s) of the AR instance(s) will be returned instead.

public static string|array getAttributeValue ( $model, $attribute )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression

return string|array

The corresponding attribute value

throws yii\base\InvalidArgumentException

if the attribute name contains non-word characters.

                public static function getAttributeValue($model, $attribute)
{
    if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
        throw new InvalidArgumentException('Attribute name must contain word characters only.');
    }
    $attribute = $matches[2];
    $value = $model->$attribute;
    if ($matches[3] !== '') {
        foreach (explode('][', trim($matches[3], '[]')) as $id) {
            if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
                $value = $value[$id];
            } else {
                return null;
            }
        }
    }
    // https://github.com/yiisoft/yii2/issues/1457
    if (is_array($value)) {
        foreach ($value as $i => $v) {
            if ($v instanceof ActiveRecordInterface) {
                $v = $v->getPrimaryKey(false);
                $value[$i] = is_array($v) ? json_encode($v) : $v;
            }
        }
    } elseif ($value instanceof ActiveRecordInterface) {
        $value = $value->getPrimaryKey(false);
        return is_array($value) ? json_encode($value) : $value;
    }
    return $value;
}

            
getInputId() public static method

Defined in: yii\helpers\BaseHtml::getInputId()

Generates an appropriate input ID for the specified attribute name or expression.

public static string getInputId ( $model, $attribute )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for explanation of attribute expression.

return string

The generated input ID.

throws yii\base\InvalidArgumentException

if the attribute name contains non-word characters.

                public static function getInputId($model, $attribute)
{
    $name = static::getInputName($model, $attribute);
    return static::getInputIdByName($name);
}

            
getInputIdByName() public static method (available since version 2.0.43)

Defined in: yii\helpers\BaseHtml::getInputIdByName()

Converts input name to ID.

For example, if $name is Post[content], this method will return post-content.

public static string getInputIdByName ( $name )
$name string

The input name

return string

The generated input ID

                public static function getInputIdByName($name)
{
    $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
    $name = mb_strtolower($name, $charset);
    return str_replace(['[]', '][', '[', ']', ' ', '.', '--'], ['', '-', '-', '', '-', '-', '-'], $name);
}

            
getInputName() public static method

Defined in: yii\helpers\BaseHtml::getInputName()

Generates an appropriate input name for the specified attribute name or expression.

This method generates a name that can be used as the input name to collect user input for the specified attribute. The name is generated according to the form name of the model and the given attribute name. For example, if the form name of the Post model is Post, then the input name generated for the content attribute would be Post[content].

See getAttributeName() for explanation of attribute expression.

public static string getInputName ( $model, $attribute )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression

return string

The generated input name

throws yii\base\InvalidArgumentException

if the attribute name contains non-word characters.

                public static function getInputName($model, $attribute)
{
    $formName = $model->formName();
    if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
        throw new InvalidArgumentException('Attribute name must contain word characters only.');
    }
    $prefix = $matches[1];
    $attribute = $matches[2];
    $suffix = $matches[3];
    if ($formName === '' && $prefix === '') {
        return $attribute . $suffix;
    } elseif ($formName !== '') {
        return $formName . $prefix . "[$attribute]" . $suffix;
    }
    throw new InvalidArgumentException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
}

            
hiddenInput() public static method

Defined in: yii\helpers\BaseHtml::hiddenInput()

Generates a hidden input field.

public static string hiddenInput ( $name, $value null, $options = [] )
$name string

The name attribute.

$value string|null

The value attribute. If it is null, the value attribute will not be generated.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated hidden input tag

                public static function hiddenInput($name, $value = null, $options = [])
{
    return static::input('hidden', $name, $value, $options);
}

            
img() public static method

Defined in: yii\helpers\BaseHtml::img()

Generates an image tag.

public static string img ( $src, $options = [] )
$src array|string

The image URL. This parameter will be processed by yii\helpers\Url::to().

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

Since version 2.0.12 It is possible to pass the srcset option as an array which keys are descriptors and values are URLs. All URLs will be processed by yii\helpers\Url::to().

return string

The generated image tag.

                public static function img($src, $options = [])
{
    $options['src'] = Url::to($src);
    if (isset($options['srcset']) && is_array($options['srcset'])) {
        $srcset = [];
        foreach ($options['srcset'] as $descriptor => $url) {
            $srcset[] = Url::to($url) . ' ' . $descriptor;
        }
        $options['srcset'] = implode(',', $srcset);
    }
    if (!isset($options['alt'])) {
        $options['alt'] = '';
    }
    return static::tag('img', '', $options);
}

            
input() public static method

Defined in: yii\helpers\BaseHtml::input()

Generates an input type of the given type.

public static string input ( $type, $name null, $value null, $options = [] )
$type string

The type attribute.

$name string|null

The name attribute. If it is null, the name attribute will not be generated.

$value string|null

The value attribute. If it is null, the value attribute will not be generated.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated input tag

                public static function input($type, $name = null, $value = null, $options = [])
{
    if (!isset($options['type'])) {
        $options['type'] = $type;
    }
    $options['name'] = $name;
    $options['value'] = $value === null ? null : (string) $value;
    return static::tag('input', '', $options);
}

            
jsFile() public static method

Defined in: yii\helpers\BaseHtml::jsFile()

Generates a script tag that refers to an external JavaScript file.

See also yii\helpers\Url::to().

public static string jsFile ( $url, $options = [] )
$url string

The URL of the external JavaScript file. This parameter will be processed by yii\helpers\Url::to().

$options array

The tag options in terms of name-value pairs. The following option is specially handled:

  • condition: specifies the conditional comments for IE, e.g., lt IE 9. When this is specified, the generated script tag will be enclosed within the conditional comments. This is mainly useful for supporting old versions of IE browsers.

The rest of the options will be rendered as the attributes of the resulting script tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated script tag

                public static function jsFile($url, $options = [])
{
    $options['src'] = Url::to($url);
    if (isset($options['condition'])) {
        $condition = $options['condition'];
        unset($options['condition']);
        return self::wrapIntoCondition(static::tag('script', '', $options), $condition);
    }
    return static::tag('script', '', $options);
}

            
label() public static method

Defined in: yii\helpers\BaseHtml::label()

Generates a label tag.

public static string label ( $content, $for null, $options = [] )
$content string

Label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, you should encode() it to prevent XSS attacks.

$for string|null

The ID of the HTML element that this label is associated with. If this is null, the "for" attribute will not be generated.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated label tag

                public static function label($content, $for = null, $options = [])
{
    $options['for'] = $for;
    return static::tag('label', $content, $options);
}

            
listBox() public static method

Defined in: yii\helpers\BaseHtml::listBox()

Generates a list box.

public static string listBox ( $name, $selection null, $items = [], $options = [] )
$name string

The input name

$selection string|boolean|array|null

The selected value(s). String for single or array for multiple selection(s).

$items array

The option data items. The array keys are option values, and the array values are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). For each sub-array, an option group will be generated whose label is the key associated with the sub-array. If you have a list of data models, you may convert them into the format described above using yii\helpers\ArrayHelper::map().

Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in the labels will also be HTML-encoded.

$options array

The tag options in terms of name-value pairs. The following options are specially handled:

  • prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array to override the value and to set other tag attributes:

    ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
    
  • options: array, the attributes for the select option tags. The array keys must be valid option values, and the array values are the extra attributes for the corresponding option tags. For example,

    [
        'value1' => ['disabled' => true],
        'value2' => ['label' => 'value 2'],
    ];
    
  • groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options', except that the array keys represent the optgroup labels specified in $items.
  • unselect: string, the value that will be submitted when no option is selected. When this attribute is set, a hidden field will be generated so that if no option is selected in multiple mode, we can still obtain the posted unselect value.
  • encodeSpaces: bool, whether to encode spaces in option prompt and option value with &nbsp; character. Defaults to false.
  • encode: bool, whether to encode option prompt and option value characters. Defaults to true. This option is available since 2.0.3.
  • strict: boolean, if $selection is an array and this value is true a strict comparison will be performed on $items keys. Defaults to false. This option is available since 2.0.37.

The rest of the options will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated list box tag

                public static function listBox($name, $selection = null, $items = [], $options = [])
{
    if (!array_key_exists('size', $options)) {
        $options['size'] = 4;
    }
    if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) {
        $name .= '[]';
    }
    $options['name'] = $name;
    if (isset($options['unselect'])) {
        // add a hidden field so that if the list box has no option being selected, it still submits a value
        if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) {
            $name = substr($name, 0, -2);
        }
        $hiddenOptions = [];
        // make sure disabled input is not sending any value
        if (!empty($options['disabled'])) {
            $hiddenOptions['disabled'] = $options['disabled'];
        }
        $hidden = static::hiddenInput($name, $options['unselect'], $hiddenOptions);
        unset($options['unselect']);
    } else {
        $hidden = '';
    }
    $selectOptions = static::renderSelectOptions($selection, $items, $options);
    return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
}

            
mailto() public static method

Defined in: yii\helpers\BaseHtml::mailto()

Generates a mailto hyperlink.

public static string mailto ( $text, $email null, $options = [] )
$text string

Link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is coming from end users, you should consider encode() it to prevent XSS attacks.

$email string|null

Email address. If this is null, the first parameter (link body) will be treated as the email address and used.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated mailto link

                public static function mailto($text, $email = null, $options = [])
{
    $options['href'] = 'mailto:' . ($email === null ? $text : $email);
    return static::tag('a', $text, $options);
}

            
ol() public static method

Defined in: yii\helpers\BaseHtml::ol()

Generates an ordered list.

public static string ol ( $items, $options = [] )
$items array|Traversable

The items for generating the list. Each item generates a single list item. Note that items will be automatically HTML encoded if $options['encode'] is not set or true.

$options array

Options (name => config) for the radio button list. The following options are supported:

  • encode: boolean, whether to HTML-encode the items. Defaults to true. This option is ignored if the item option is specified.
  • itemOptions: array, the HTML attributes for the li tags. This option is ignored if the item option is specified.
  • item: callable, a callback that is used to generate each individual list item. The signature of this callback must be:

    function ($item, $index)
    

    where $index is the array key corresponding to $item in $items. The callback should return the whole list item tag.

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated ordered list. An empty string is returned if $items is empty.

                public static function ol($items, $options = [])
{
    $options['tag'] = 'ol';
    return static::ul($items, $options);
}

            
passwordInput() public static method

Defined in: yii\helpers\BaseHtml::passwordInput()

Generates a password input field.

public static string passwordInput ( $name, $value null, $options = [] )
$name string

The name attribute.

$value string|null

The value attribute. If it is null, the value attribute will not be generated.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated password input tag

                public static function passwordInput($name, $value = null, $options = [])
{
    return static::input('password', $name, $value, $options);
}

            
radio() public static method

Defined in: yii\helpers\BaseHtml::radio()

Generates a radio button input.

public static string radio ( $name, $checked false, $options = [] )
$name string

The name attribute.

$checked boolean

Whether the radio button should be checked.

$options array

The tag options in terms of name-value pairs. See booleanInput() for details about accepted attributes.

return string

The generated radio button tag

                public static function radio($name, $checked = false, $options = [])
{
    return static::booleanInput('radio', $name, $checked, $options);
}

            
radioList() public static method

Defined in: yii\helpers\BaseHtml::radioList()

Generates a list of radio buttons.

A radio button list is like a checkbox list, except that it only allows single selection.

public static string radioList ( $name, $selection null, $items = [], $options = [] )
$name string

The name attribute of each radio button.

$selection string|array|null

The selected value(s). String for single or array for multiple selection(s).

$items array

The data item used to generate the radio buttons. The array keys are the radio button values, while the array values are the corresponding labels.

$options array

Options (name => config) for the radio button list container tag. The following options are specially handled:

  • tag: string|false, the tag name of the container element. False to render radio buttons without container. See also tag().
  • unselect: string, the value that should be submitted when none of the radio buttons is selected. By setting this option, a hidden input will be generated.
  • disabled: boolean, whether the generated by unselect option hidden input should be disabled. Defaults to false. This option is available since version 2.0.16.
  • encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true. This option is ignored if item option is set.
  • strict: boolean, if $selection is an array and this value is true a strict comparison will be performed on $items keys. Defaults to false. This option is available since 2.0.37.
  • separator: string, the HTML code that separates items.
  • itemOptions: array, the options for generating the radio button tag using radio().
  • item: callable, a callback that can be used to customize the generation of the HTML code corresponding to a single item in $items. The signature of this callback must be:

    function ($index, $label, $name, $checked, $value)
    

    where $index is the zero-based index of the radio button in the whole list; $label is the label for the radio button; and $name, $value and $checked represent the name, value and the checked status of the radio button input, respectively.

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated radio button list

                public static function radioList($name, $selection = null, $items = [], $options = [])
{
    if (ArrayHelper::isTraversable($selection)) {
        $selection = array_map('strval', ArrayHelper::toArray($selection));
    }
    $formatter = ArrayHelper::remove($options, 'item');
    $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
    $encode = ArrayHelper::remove($options, 'encode', true);
    $separator = ArrayHelper::remove($options, 'separator', "\n");
    $tag = ArrayHelper::remove($options, 'tag', 'div');
    $strict = ArrayHelper::remove($options, 'strict', false);
    $hidden = '';
    if (isset($options['unselect'])) {
        // add a hidden field so that if the list box has no option being selected, it still submits a value
        $hiddenOptions = [];
        // make sure disabled input is not sending any value
        if (!empty($options['disabled'])) {
            $hiddenOptions['disabled'] = $options['disabled'];
        }
        $hidden =  static::hiddenInput($name, $options['unselect'], $hiddenOptions);
        unset($options['unselect'], $options['disabled']);
    }
    $lines = [];
    $index = 0;
    foreach ($items as $value => $label) {
        $checked = $selection !== null &&
            (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
                || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, $selection, $strict));
        if ($formatter !== null) {
            $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
        } else {
            $lines[] = static::radio($name, $checked, array_merge([
                'value' => $value,
                'label' => $encode ? static::encode($label) : $label,
            ], $itemOptions));
        }
        $index++;
    }
    $visibleContent = implode($separator, $lines);
    if ($tag === false) {
        return $hidden . $visibleContent;
    }
    return $hidden . static::tag($tag, $visibleContent, $options);
}

            
removeCssClass() public static method

Defined in: yii\helpers\BaseHtml::removeCssClass()

Removes a CSS class from the specified options.

See also addCssClass().

public static void removeCssClass ( &$options, $class )
$options array

The options to be modified.

$class string|array

The CSS class(es) to be removed

                public static function removeCssClass(&$options, $class)
{
    if (isset($options['class'])) {
        if (is_array($options['class'])) {
            $classes = array_diff($options['class'], (array) $class);
            if (empty($classes)) {
                unset($options['class']);
            } else {
                $options['class'] = $classes;
            }
        } else {
            $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
            $classes = array_diff($classes, (array) $class);
            if (empty($classes)) {
                unset($options['class']);
            } else {
                $options['class'] = implode(' ', $classes);
            }
        }
    }
}

            
removeCssStyle() public static method

Defined in: yii\helpers\BaseHtml::removeCssStyle()

Removes the specified CSS style from the HTML options.

For example,

Html::removeCssStyle($options, ['width', 'height']);

See also addCssStyle().

public static void removeCssStyle ( &$options, $properties )
$options array

The HTML options to be modified.

$properties string|array

The CSS properties to be removed. You may use a string if you are removing a single property.

                public static function removeCssStyle(&$options, $properties)
{
    if (!empty($options['style'])) {
        $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
        foreach ((array) $properties as $property) {
            unset($style[$property]);
        }
        $options['style'] = static::cssStyleFromArray($style);
    }
}

            
renderSelectOptions() public static method

Defined in: yii\helpers\BaseHtml::renderSelectOptions()

Renders the option tags that can be used by dropDownList() and listBox().

public static string renderSelectOptions ( $selection, $items, &$tagOptions = [] )
$selection string|array|boolean|null

The selected value(s). String/boolean for single or array for multiple selection(s).

$items array

The option data items. The array keys are option values, and the array values are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too). For each sub-array, an option group will be generated whose label is the key associated with the sub-array. If you have a list of data models, you may convert them into the format described above using yii\helpers\ArrayHelper::map().

Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in the labels will also be HTML-encoded.

$tagOptions array

The $options parameter that is passed to the dropDownList() or listBox() call. This method will take out these elements, if any: "prompt", "options" and "groups". See more details in dropDownList() for the explanation of these elements.

return string

The generated list options

                public static function renderSelectOptions($selection, $items, &$tagOptions = [])
{
    if (ArrayHelper::isTraversable($selection)) {
        $normalizedSelection = [];
        foreach (ArrayHelper::toArray($selection) as $selectionItem) {
            if (is_bool($selectionItem)) {
                $normalizedSelection[] = $selectionItem ? '1' : '0';
            } else {
                $normalizedSelection[] = (string)$selectionItem;
            }
        }
        $selection = $normalizedSelection;
    } elseif (is_bool($selection)) {
        $selection = $selection ? '1' : '0';
    }
    $lines = [];
    $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
    $encode = ArrayHelper::remove($tagOptions, 'encode', true);
    $strict = ArrayHelper::remove($tagOptions, 'strict', false);
    if (isset($tagOptions['prompt'])) {
        $promptOptions = ['value' => ''];
        if (is_string($tagOptions['prompt'])) {
            $promptText = $tagOptions['prompt'];
        } else {
            $promptText = $tagOptions['prompt']['text'];
            $promptOptions = array_merge($promptOptions, $tagOptions['prompt']['options']);
        }
        $promptText = $encode ? static::encode($promptText) : $promptText;
        if ($encodeSpaces) {
            $promptText = str_replace(' ', '&nbsp;', $promptText);
        }
        $lines[] = static::tag('option', $promptText, $promptOptions);
    }
    $options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
    $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
    unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
    $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
    $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
    foreach ($items as $key => $value) {
        if (is_array($value)) {
            $groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
            if (!isset($groupAttrs['label'])) {
                $groupAttrs['label'] = $key;
            }
            $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode, 'strict' => $strict];
            $content = static::renderSelectOptions($selection, $value, $attrs);
            $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
        } else {
            $attrs = isset($options[$key]) ? $options[$key] : [];
            $attrs['value'] = (string) $key;
            if (!array_key_exists('selected', $attrs)) {
                $selected = false;
                if ($selection !== null) {
                    if (ArrayHelper::isTraversable($selection)) {
                        $selected = ArrayHelper::isIn((string)$key, $selection, $strict);
                    } elseif ($key === '' || $selection === '') {
                        $selected = $selection === $key;
                    } elseif ($strict) {
                        $selected = !strcmp((string)$key, (string)$selection);
                    } else {
                        $selected = $selection == $key;
                    }
                }
                $attrs['selected'] = $selected;
            }
            $text = $encode ? static::encode($value) : $value;
            if ($encodeSpaces) {
                $text = str_replace(' ', '&nbsp;', $text);
            }
            $lines[] = static::tag('option', $text, $attrs);
        }
    }
    return implode("\n", $lines);
}

            
renderTagAttributes() public static method

Defined in: yii\helpers\BaseHtml::renderTagAttributes()

Renders the HTML tag attributes.

Attributes whose values are of boolean type will be treated as boolean attributes.

Attributes whose values are null will not be rendered.

The values of attributes will be HTML-encoded using encode().

aria and data attributes get special handling when they are set to an array value. In these cases, the array will be "expanded" and a list of ARIA/data attributes will be rendered. For example, 'aria' => ['role' => 'checkbox', 'value' => 'true'] would be rendered as aria-role="checkbox" aria-value="true".

If a nested data value is set to an array, it will be JSON-encoded. For example, 'data' => ['params' => ['id' => 1, 'name' => 'yii']] would be rendered as data-params='{"id":1,"name":"yii"}'.

See also addCssClass().

public static string renderTagAttributes ( $attributes )
$attributes array

Attributes to be rendered. The attribute values will be HTML-encoded using encode().

return string

The rendering result. If the attributes are not empty, they will be rendered into a string with a leading white space (so that it can be directly appended to the tag name in a tag). If there is no attribute, an empty string will be returned.

                public static function renderTagAttributes($attributes)
{
    if (count($attributes) > 1) {
        $sorted = [];
        foreach (static::$attributeOrder as $name) {
            if (isset($attributes[$name])) {
                $sorted[$name] = $attributes[$name];
            }
        }
        $attributes = array_merge($sorted, $attributes);
    }
    $html = '';
    foreach ($attributes as $name => $value) {
        if (is_bool($value)) {
            if ($value) {
                $html .= " $name";
            }
        } elseif (is_array($value)) {
            if (in_array($name, static::$dataAttributes)) {
                foreach ($value as $n => $v) {
                    if (is_array($v)) {
                        $html .= " $name-$n='" . Json::htmlEncode($v) . "'";
                    } elseif (is_bool($v)) {
                        if ($v) {
                            $html .= " $name-$n";
                        }
                    } elseif ($v !== null) {
                        $html .= " $name-$n=\"" . static::encode($v) . '"';
                    }
                }
            } elseif ($name === 'class') {
                if (empty($value)) {
                    continue;
                }
                if (static::$normalizeClassAttribute === true && count($value) > 1) {
                    // removes duplicate classes
                    $value = explode(' ', implode(' ', $value));
                    $value = array_unique($value);
                }
                $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
            } elseif ($name === 'style') {
                if (empty($value)) {
                    continue;
                }
                $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
            } else {
                $html .= " $name='" . Json::htmlEncode($value) . "'";
            }
        } elseif ($value !== null) {
            $html .= " $name=\"" . static::encode($value) . '"';
        }
    }
    return $html;
}

            
resetButton() public static method

Defined in: yii\helpers\BaseHtml::resetButton()

Generates a reset button tag.

public static string resetButton ( $content 'Reset', $options = [] )
$content string

The content enclosed within the button tag. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, you should consider encode() it to prevent XSS attacks.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated reset button tag

                public static function resetButton($content = 'Reset', $options = [])
{
    $options['type'] = 'reset';
    return static::button($content, $options);
}

            
resetInput() public static method

Defined in: yii\helpers\BaseHtml::resetInput()

Generates a reset input button.

public static string resetInput ( $label 'Reset', $options = [] )
$label string|null

The value attribute. If it is null, the value attribute will not be generated.

$options array

The attributes of the button tag. The values will be HTML-encoded using encode(). Attributes whose value is null will be ignored and not put in the tag returned. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated button tag

                public static function resetInput($label = 'Reset', $options = [])
{
    $options['type'] = 'reset';
    $options['value'] = $label;
    return static::tag('input', '', $options);
}

            
script() public static method

Defined in: yii\helpers\BaseHtml::script()

Generates a script tag.

public static string script ( $content, $options = [] )
$content string

The script content

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated script tag

                public static function script($content, $options = [])
{
    return static::tag('script', $content, $options);
}

            
setActivePlaceholder() protected static method (available since version 2.0.14)

Defined in: yii\helpers\BaseHtml::setActivePlaceholder()

Generate placeholder from model attribute label.

protected static void setActivePlaceholder ( $model, $attribute, &$options = [] )
$model yii\base\Model

The model object

$attribute string

The attribute name or expression. See getAttributeName() for the format about attribute expression.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode().

                protected static function setActivePlaceholder($model, $attribute, &$options = [])
{
    if (isset($options['placeholder']) && $options['placeholder'] === true) {
        $attribute = static::getAttributeName($attribute);
        $options['placeholder'] = $model->getAttributeLabel($attribute);
    }
}

            
style() public static method

Defined in: yii\helpers\BaseHtml::style()

Generates a style tag.

public static string style ( $content, $options = [] )
$content string

The style content

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated style tag

                public static function style($content, $options = [])
{
    return static::tag('style', $content, $options);
}

            
submitButton() public static method

Defined in: yii\helpers\BaseHtml::submitButton()

Generates a submit button tag.

Be careful when naming form elements such as submit buttons. According to the jQuery documentation there are some reserved names that can cause conflicts, e.g. submit, length, or method.

public static string submitButton ( $content 'Submit', $options = [] )
$content string

The content enclosed within the button tag. It will NOT be HTML-encoded. Therefore you can pass in HTML code such as an image tag. If this is is coming from end users, you should consider encode() it to prevent XSS attacks.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated submit button tag

                public static function submitButton($content = 'Submit', $options = [])
{
    $options['type'] = 'submit';
    return static::button($content, $options);
}

            
submitInput() public static method

Defined in: yii\helpers\BaseHtml::submitInput()

Generates a submit input button.

Be careful when naming form elements such as submit buttons. According to the jQuery documentation there are some reserved names that can cause conflicts, e.g. submit, length, or method.

public static string submitInput ( $label 'Submit', $options = [] )
$label string|null

The value attribute. If it is null, the value attribute will not be generated.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated button tag

                public static function submitInput($label = 'Submit', $options = [])
{
    $options['type'] = 'submit';
    $options['value'] = $label;
    return static::tag('input', '', $options);
}

            
tag() public static method

Defined in: yii\helpers\BaseHtml::tag()

Generates a complete HTML tag.

See also:

public static string tag ( $name, $content '', $options = [] )
$name string|boolean|null

The tag name. If $name is null or false, the corresponding content will be rendered without any tag.

$content string

The content to be enclosed between the start and end tags. It will not be HTML-encoded. If this is coming from end users, you should consider encode() it to prevent XSS attacks.

$options array

The HTML tag attributes (HTML options) in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered.

For example when using ['class' => 'my-class', 'target' => '_blank', 'value' => null] it will result in the html attributes rendered like this: class="my-class" target="_blank".

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated HTML tag

                public static function tag($name, $content = '', $options = [])
{
    if ($name === null || $name === false) {
        return $content;
    }
    $html = "<$name" . static::renderTagAttributes($options) . '>';
    return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>";
}

            
textInput() public static method

Defined in: yii\helpers\BaseHtml::textInput()

Generates a text input field.

public static string textInput ( $name, $value null, $options = [] )
$name string

The name attribute.

$value string|null

The value attribute. If it is null, the value attribute will not be generated.

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated text input tag

                public static function textInput($name, $value = null, $options = [])
{
    return static::input('text', $name, $value, $options);
}

            
textarea() public static method

Defined in: yii\helpers\BaseHtml::textarea()

Generates a text area input.

public static string textarea ( $name, $value '', $options = [] )
$name string

The input name

$value string

The input value. Note that it will be encoded using encode().

$options array

The tag options in terms of name-value pairs. These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using encode(). If a value is null, the corresponding attribute will not be rendered. See renderTagAttributes() for details on how attributes are being rendered. The following special options are recognized:

  • doubleEncode: whether to double encode HTML entities in $value. If false, HTML entities in $value will not be further encoded. This option is available since version 2.0.11.
return string

The generated text area tag

                public static function textarea($name, $value = '', $options = [])
{
    $options['name'] = $name;
    $doubleEncode = ArrayHelper::remove($options, 'doubleEncode', true);
    return static::tag('textarea', static::encode($value, $doubleEncode), $options);
}

            
ul() public static method

Defined in: yii\helpers\BaseHtml::ul()

Generates an unordered list.

public static string ul ( $items, $options = [] )
$items array|Traversable

The items for generating the list. Each item generates a single list item. Note that items will be automatically HTML encoded if $options['encode'] is not set or true.

$options array

Options (name => config) for the radio button list. The following options are supported:

  • encode: boolean, whether to HTML-encode the items. Defaults to true. This option is ignored if the item option is specified.
  • separator: string, the HTML code that separates items. Defaults to a simple newline ("\n"). This option is available since version 2.0.7.
  • itemOptions: array, the HTML attributes for the li tags. This option is ignored if the item option is specified.
  • item: callable, a callback that is used to generate each individual list item. The signature of this callback must be:

    function ($item, $index)
    

    where $index is the array key corresponding to $item in $items. The callback should return the whole list item tag.

See renderTagAttributes() for details on how attributes are being rendered.

return string

The generated unordered list. An empty list tag will be returned if $items is empty.

                public static function ul($items, $options = [])
{
    $tag = ArrayHelper::remove($options, 'tag', 'ul');
    $encode = ArrayHelper::remove($options, 'encode', true);
    $formatter = ArrayHelper::remove($options, 'item');
    $separator = ArrayHelper::remove($options, 'separator', "\n");
    $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
    if (empty($items)) {
        return static::tag($tag, '', $options);
    }
    $results = [];
    foreach ($items as $index => $item) {
        if ($formatter !== null) {
            $results[] = call_user_func($formatter, $item, $index);
        } else {
            $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
        }
    }
    return static::tag(
        $tag,
        $separator . implode($separator, $results) . $separator,
        $options
    );
}