arrow_back
Back

Yii2 helpers: Html, Url, dropdown lists, and formatter

Andrew Dorokhov Andrew Dorokhov schedule 3 min read
menu_book Table of Contents

Helpers are utility classes and functions that assist in building views.

yii\helpers\Html

Every web application produces a lot of HTML markup. Static markup can be written by mixing PHP and HTML in one file, but dynamic markup becomes hard to build without help. The Html helper provides static methods for working with commonly used tags, their attributes, and content.

Escaping output

Any text coming from the database should be escaped. This protects the markup and prevents XSS attacks:

echo Html::encode($user->name);

Generating tags

<?= Html::tag('p', Html::encode($user->name), ['class' => 'username']) ?>
  • First argument — the tag name.
  • Second — the content placed between the opening and closing tags.
  • Third — an array of tag attributes.

Sometimes it is convenient to split it in two:

<?= Html::beginTag('p', ['class' => 'username']); ?>
...
<?= Html::endTag('p'); ?>

How attributes are handled

  • If the value is null, the attribute is not rendered.
  • Boolean values are treated as boolean attributes.
  • Attribute values are escaped with Html::encode().
  • If an array is passed as a value, it is handled as follows:
    • If the attribute is one of the data attributes listed in yii\helpers\Html::$dataAttributes (data, ng, data-ng), a list of attributes is generated, one per array element. For example, 'data' => ['id' => 1, 'name' => 'yii'] renders data-id="1" data-name="yii", and 'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok'] renders data-params='{"id":1,"name":"yii"}' data-status="ok" — note that nested arrays are rendered as JSON.
    • If the attribute is not a data attribute, the value is converted to JSON. For example, ['params' => ['id' => 1, 'name' => 'yii']] renders params='{"id":1,"name":"yii"}'.

Rendering forms

<?= Html::beginForm(['order/update'], 'post', ['enctype' => 'multipart/form-data']) ?>
  • First parameter — the URL the form is submitted to (in a format suitable for Url::to()).
  • Second — the submit method, post by default.
  • Third — an array of form attributes.

Closing the form tag:

<?= Html::endForm() ?>

yii\helpers\Url

The Url helper provides static methods for managing URLs.

$url = Url::to(['post/view', 'id' => 100]);

Url::to() calls UrlManager::createUrl() to build the URL.

Depending on the pretty-URL settings, the output may look like:

  • /index.php?r=post/view&id=100
  • /index.php/post/100
  • /post/100

Ways to create a URL

URL for a route (/index.php?r=post/index):

Url::to(['post/index']);

URL for a route with parameters (/index.php?r=post/view&id=100):

Url::to(['post/view', 'id' => 100]);

URL with an anchor (/index.php?r=post/view&id=100#content):

Url::to(['post/view', 'id' => 100, '#' => 'content']);

Absolute URL (http://example.com/images/logo.gif):

Url::to('/images/logo.gif', true);

Absolute URL with the https scheme (https://www.example.com/index.php?r=post/index):

Url::to(['post/index'], 'https');

URL for the current route (/index.php?r=admin/post/index):

Url::to(['']);
Url::to();

URL for a relative route with only the action ID (/index.php?r=admin/post/index):

Url::to(['index']);

URL for an absolute route (/index.php?r=post/index):

Url::to(['/post/index']);

Using an alias (@posts defined as /post/index):

Url::to(['@posts']);

Special methods

Home URL (/index.php?r=site/index):

Url::home();
<div class="form-group">
    <label class="control-label" for="group">Choose a group</label>
    <?php echo Html::dropDownList(
        'group_id',
        null,
        ArrayHelper::map($this->groups, 'id', 'name'),
        ['class' => 'form-control']
    ); ?>
</div>

With attributes for the option elements:

<?= Html::dropDownList(
    'group_id',
    null,
    ArrayHelper::map($groups, 'id', 'name'),
    [
        'class'   => 'form-control',
        'prompt'  => '-- Choose a group --',
        'id'      => 'group-select',
        'options' => [
            0 => ['data-id' => 'test'],
            5 => ['data-id' => 'test 2'],
        ],
    ]
); ?>

Attributes can also be built from a data set:

<?= Html::dropDownList(
    'group_id',
    null,
    ArrayHelper::map($groups, 'id', 'name'),
    [
        'class'   => 'form-control',
        'prompt'  => '-- Choose a group --',
        'id'      => 'group-select',
        'options' => ArrayHelper::map($groups, 'id', 'updated_at'),
    ]
); ?>

Formatting date and time

Yii::$app->formatter->asRelativeTime($timestamp); // 5 minutes ago
Yii::$app->formatter->asDateTime($timestamp);     // Aug 11, 2019, 3:11:24 PM
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

Yii2 flash messages: setFlash, hasFlash, and the Alert widget

arrow_forward