How do I override a widget method in Yii2?

I need to override the renderPageButton() method in the Yii2 LinkPager widget. The method documentation specifically says “You may override this method to customize the generation of page buttons” but I can’t figure out how to do that. Thanks.

Hi @littlebob

  1. Write your own link pager extending LinkPager:
class MyLinkPager extends \yii\widgets\LinkPager
{
    ...
    protected function renderPageButton($label, $page, $class, $disabled, $active)
    {
        ...
    }
    ...
}

You see an eye-ball icon in the description of renderPageButton() in the API reference. It will show you the original source code of it and show you some hints to customize it.

  1. Use it for your grid view (or list view) in your view
    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            [
                'attribute' => 'date',
            ],
            ...
        ],
        'pager' => ['class' => MyLinkPager::class,],
    ]); ?>

GridView::pager specifies a pager configuration. It uses \yii\widgets\LinkPager by default. So we are telling that it should use MyLinkPager instead. Check the API reference for BaseListView::$pager.

LinkPager together with BaseListView (GridView and ListView) and DataProvider is quite a powerful set of useful UI tools. So they are a bit complicated and you may need to read the docs and the source codes eagerly in order to understand and customize them.

1 Like

Perfect! Thank you