排序/每页逻辑在哪里属于基于Yii2的应用程序?

时间:2014-12-14 20:37:31

标签: php yii2

我在Yii2中有一个控制器,它将产品目录显示为产品列表。产品目录有一个控件(选择)来设置排序(流行度,价格等)和每页条目(12,24等)。

有几条逻辑,我试图把它们放在正确的层中:

  1. 可能的排序列列表和可能的每页值列表
  2. 默认排序列和默认的每页值
  3. 从请求中获取参数(即$ _GET ['sort']),如果请求为空则回退到默认值
  4. 在Yii2中实际上有一个View对象,所以可能有一些需要进入它?

1 个答案:

答案 0 :(得分:3)

在Yii2中,ModelNameSearch.php会处理这个问题。这就是我设置它的方式(不完全是这个,但这是简单的版本):

在控制器中

/**
 * Sets the pagination for the list
 * @return mixed
 */
public function actionPagination()
{
    TagSearch::setPerPage(Yii::$app->request->queryParams['records']);
    $this->redirect(['index']);
}

在TagSearch中

    public function setPerPage($recordPerPage)
    {
        Yii::$app->session->set(self::className() . 'Pagination', $recordPerPage);
    }

    public function getPerPage()
    {
        return Yii::$app->session->get(self::className() . 'Pagination', 25),
    }

.....................
    public function search($params)
    {
..............................
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => self::getPerPage()
            ],
        ]);
......................
}

在视图中随意做

<?= Html::dropDownList('pagination', TagSearch::getPerPage(), ['10' => '10 per page', '25' => '25 per page', '50' => '50 per page', '100' => '100 per page'], ['class' => "form-control input-sm pagination", 'data-change'=> Url::toRoute('pagination')]) ?>

并添加

$('select.pagination').on('change', function() {
    document.location.href = $(this).attr('data-change') + '?records=' + $(this).val();
});

我需要自己查看变量的命名,上面的代码中可能有错误(我写的是复制粘贴和更改),但是你明白了。