LoginSignup
2
2

More than 5 years have passed since last update.

Yii 2 で Sort リンクをクリックしたときにページを 1 ページ目に戻す方法

Posted at

はじめに

デフォルトでは \yii\data\Sort クラスでリンクを作成する場合、ページが 3 ページ目ならば page=3 というパラメータを引き継いだままソートされます。これをソートリンクをクリックしたときにはページは 1 ページ目になるようにカスタマイズしてみます。

一応、GitHub の issue にもありますが、放置気味なので今後どうなるかはよくわかりません。
https://github.com/yiisoft/yii2/issues/4790

Sort クラスを継承してカスタマイズする

\yii\data\Sort クラスを継承した独自の Sort クラスを作成。createUrl() で GET パラメーターの処理が書かれているみたいなので、処理の間に page パラメータがあればそれを削除する、みたいなコードを書き足しました:

Sort.php
<?php

namespace app\data;

use Yii;

class Sort extends \yii\data\Sort
{
    /**
     * Returns the page paramater.
     * @return string
     */
    public function getPageParam()
    {
        return (new \yii\data\Pagination())->pageParam;
    }

    /**
     * @inheritdoc
     */
    public function createUrl($attribute, $absolute = false)
    {
        $params = $this->params;

        if ($params === null) {
            $request = Yii::$app->getRequest();
            $params = $request instanceof Request
                ? $request->getQueryParams()
                : [];
        }
        if (isset($params[$this->getPageParam()])) {
            unset($params[$this->getPageParam()]);
        }
        $params[$this->sortParam] = $this->createSortParam($attribute);

        $params[0] = $this->route === null
            ? Yii::$app->controller->getRoute()
            : $this->route;

        $urlManager = $this->urlManager === null
            ? Yii::$app->getUrlManager()
            : $this->urlManager;

        if ($absolute) {
            return $urlManager->createAbsoluteUrl($params);
        } else {
            return $urlManager->createUrl($params);
        }
    }
}

\yii\data\Sort をすべて独自のものに変更する

あとは今までのものをすべて独自のクラスを使うように設定します:

\Yii::$container->set('yii\data\Sort', [
    'class' => 'app\data\Sort',
]);
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2