When data needs to be rendered in multiple pages, Pagination can be used to
represent information such as [[totalCount|total item count]], [[pageSize|page size]],
[[page|current page]], etc. These information can be passed to [[yii\widgets\Pager|pagers]]
to render pagination buttons or links.
The following example shows how to create a pagination object and feed it
to a pager.
Controller action:
~~~
function actionIndex()
{
$query = Article::find()->where(['status' => 1]);
$countQuery = clone $query;
$pages = new Pagination(['totalCount' => $countQuery->count()]);
$models = $query->offset($pages->offset)
->limit($pages->limit)
->all();
return $this->render('index', [
'models' => $models,
'pages' => $pages,
]);
}
~~~
View:
~~~
foreach ($models as $model) {
display $model here
}
display pagination
echo LinkPager::widget([
'pagination' => $pages,
]);
~~~
/** * Creates an url for the specified page size. * @param \yii\data\Pagination $pagination * @param integer $pageSize page size * @param boolean $absolute whether to create an absolute URL. Defaults to `false`. * * @return string the created URL */ public static function createSizeUrl($pagination, $pageSize, $absolute = false) { if (($params = $pagination->params) === null) { $request = Yii::$app->getRequest(); $params = $request instanceof Request ? $request->getQueryParams() : []; } $currentPageSize = $pagination->getPageSize(); $currentPage = $pagination->getPage(); $target = $currentPage * $currentPageSize; $page = (int) ($target / $pageSize); if ($page > 0 || $page >= 0 && $pagination->forcePageParam) { $params[$pagination->pageParam] = $page + 1; } else { unset($params[$pagination->pageParam]); } if ($pageSize != $pagination->defaultPageSize) { $params[$pagination->pageSizeParam] = $pageSize; } else { unset($params[$pagination->pageSizeParam]); } $params[0] = $pagination->route === null ? Yii::$app->controller->getRoute() : $pagination->route; $urlManager = $pagination->urlManager === null ? Yii::$app->getUrlManager() : $pagination->urlManager; if ($absolute) { return $urlManager->createAbsoluteUrl($params); } else { return $urlManager->createUrl($params); } }
/** * Shows user's profile. * @param integer $id * @return \yii\web\Response * @throws \yii\web\NotFoundHttpException */ public function actionShow($id) { $this->enableCsrfValidation = false; $profile = $this->finder->findProfileById($id); if ($profile === null) { throw new NotFoundHttpException(); } $query = Comments::find()->where(['deleted' => Comments::NO_DELETED, 'user_id' => $id])->orderBy('created_at'); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(10); $comments = $query->offset($pages->offset)->limit($pages->limit)->all(); $model = new Comments(); $this->performAjaxValidation($model); $user = User::findOne(Yii::$app->user->getId()); if ($model->load(Yii::$app->request->post())) { $model->created_at = time(); $model->user_id = $profile->user->getId(); $model->sender_id = Yii::$app->user->getId(); $model->save(); return $this->refresh(); } else { return $this->render('show', ['profile' => $profile, 'model' => $model, 'user' => $user, 'comments' => $comments, 'pages' => $pages]); } return $this->render('show', ['profile' => $profile]); }
public function getListByCategory($slug, $fields = [], $with = [], $page = false, $pageSize = false, $order = '') { $category = Category::getInstance()->getBySlug($slug); $model = self::$model->find()->select($fields)->where(['type' => Content::TYPE_ARTICLE, 'status' => Content::STATUS_ACTIVE, 'meta_id' => $category['id']])->join('RIGHT JOIN', Relationship::tableName() . ' relation', 'content_id=id'); $countModel = clone $model; $pagination = new Pagination(['totalCount' => $countModel->count(), 'pageSize' => $pageSize]); if ($page) { $pagination->setPage($page, true); } switch (strtoupper($order)) { case 'VIEW': $model->orderBy('view_total DESC'); break; case 'COMMENT': $model->orderBy('comment_total DESC'); break; case 'CREATED': $model->orderBy('created_at DESC'); break; case 'UPDATED': $model->orderBy('updated_at DESC'); break; } return ['data' => $model->with($with)->limit($pagination->getLimit())->offset($pagination->getOffset())->all(), 'pagination' => $pagination]; }
public static function getPagedRows($query, $tablename, $params, $config = []) { $countQuery = clone $query; if (isset($params['SqlAttackSearch']) || isset($params['SqlLogSearch']) || isset($params['ErrorLogSearch'])) { //$rownums['nums'] = $countQuery->count(); //在条件查询时不处理分页,给一个大概数 $rownums['nums'] = 10000000; } else { $rownums = Yii::$app->db->createCommand("select TABLE_ROWS nums from information_schema.TABLES where TABLE_SCHEMA='Tuandai_Log' and TABLE_NAME='" . $tablename . "'")->queryOne(); } $pages = new Pagination(['totalCount' => $rownums['nums']]); if (isset($config['pageSize'])) { $pages->setPageSize($config['pageSize'], true); } $rows = $query->offset($pages->offset)->limit($pages->limit); if (isset($config['orderBy'])) { $rows = $rows->orderBy($config['orderBy']); } $rows = $rows->all(); $rowsLable = 'datas'; $pagesLable = 'pager'; if (isset($config['rows'])) { $rowsLable = $config['rows']; } if (isset($config['pages'])) { $pagesLable = $config['pages']; } $ret = []; $ret[$rowsLable] = $rows; $ret[$pagesLable] = $pages; return $ret; }
public function actionSearch($keyword, $category_id = NULL, $order = NULL, $image_only = NULL, $h24_only = NULL) { $this->layout = 'create_list'; $key = explode(' ', $keyword); $key = array_filter($key); $info_c = Info::find()->select(['category_id'])->where(['or like', 'title', $key])->groupBy(['category_id'])->all(); $query = Info::find(); if ($category_id) { $query->where(['and', ['category_id' => $category_id], ['or like', 'title', $key]]); } else { $query->where(['and', ['category_id' => isset($info_c[0]) ? $info_c[0]->category_id : ''], ['or like', 'title', $key]]); } if ($image_only) { $query->andWhere(['and', 'photo is not null']); } if ($h24_only) { $query->andWhere(['and', 'time > ' . strtotime("-1 day")]); } if ($order) { $query->orderBy(str_replace('_', ' ', $order)); } $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(10, true); $data = $query->offset($pages->offset)->limit($pages->limit)->all(); foreach ($key as $k => $v) { $key[$k] = "/(" . $v . ")/i"; } foreach ($data as $k => $v) { $data[$k]->title = preg_replace($key, "<span style='color:red;'>\$1</span>", $data[$k]->title); } return $this->render('search', ['info_c' => $info_c, 'data' => $data, 'pages' => $pages]); }
/** * @param Pagination $pagination * @return string */ protected function getPage(Pagination $pagination) { $page = $pagination->getPage() + 1; if ($page == 1) { return ''; } return ' (' . Yii::t('forum', 'Page number', ['page' => $page]) . ')'; }
/** * @return Pagination */ public function getPaginator() { $paginator = new Pagination(['totalCount' => $this->countQuery->count()]); $paginator->pageParam = 'page'; $paginator->pageSizeParam = false; $paginator->setPageSize($this->limit); return $paginator; }
/** * 个人歌单 * @param $userId * @return array */ public function personalSongKingdomByUserId($userId) { $query = SongKingdom::find()->andWhere(['created_by' => $userId]); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(10); $models = $query->offset($pages->offset)->limit($pages->limit)->all(); return ['models' => $models, 'pages' => $pages, 'userCreadedBy' => User::find()->andWhere(['id' => $userId])->asArray()->one(), 'userExtendCreadedBy' => UserExtend::find()->andWhere(['user_id' => $userId])->asArray()->one()]; }
public function actionIndex() { $query = Ads::find()->where(['deleted' => Ads::NO_DELETED])->orderBy('created_at'); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(20); $ads = $query->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('index', ['ads' => $ads, 'pages' => $pages]); }
public function getList($fields = [], $with = [], $pageSize = false, $page = false) { $model = self::$model->find()->where(['type' => Meta::TYPE_ARTICLE_CATEGORIES, 'status' => Meta::STATUS_ACTIVE]); $countModel = clone $model; $pagination = new Pagination(['totalCount' => $countModel->count('id'), 'pageSize' => $pageSize]); if ($page) { $pagination->setPage($page, true); } return ['data' => $model->with($with)->select($fields)->offset($pagination->getOffset())->limit($pagination->getLimit())->asArray()->all(), 'pagination' => $pagination]; }
public static function getTags($fields = [], $with = [], $pageSize = false, $page = false) { $model = Meta::find()->where(['type' => Meta::TYPE_TAG, 'status' => Meta::STATUS_ACTIVE]); $countModel = clone $model; $pagination = new Pagination(['totalCount' => $countModel->count('id'), 'pageSize' => $pageSize]); if ($page) { $pagination->setPage($page, true); } return ['data' => $model->select($fields)->with($with)->limit($pagination->getLimit())->offset($pagination->getOffset())->orderBy('created_at desc')->asArray()->all(), 'pagination' => $pagination]; }
/** * sitemap * @return string */ public function actionSitemap() { /* header */ Yii::$app->response->format = Response::FORMAT_RAW; $headers = Yii::$app->response->headers; $headers->add('Content-Type', 'application/xml'); /* ok */ $query = PageData::find()->select(['id_page', 'language', 'updated_at'])->where(['status' => PageData::STATUS_ACTIVE]); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(Yii::$app->params['sitemapPageSize']); $models = $query->offset($pages->offset)->limit($pages->limit)->all(); return $this->renderPartial('sitemap', ['models' => $models]); }
public function actionTypes() { $current_mode = 1; if (Yii::$app->request->get('mode')) { $current_mode = Yii::$app->request->get('mode'); } $features_types_model = new FeaturesTypes(); if ($features_types_model->load(Yii::$app->request->post())) { $features_types_model->add(); } $features_query = Features::find(); $pages = new Pagination(['totalCount' => $features_query->count()]); $pages->setPageSize(Features::FEATURES_PER_PAGE); $features_list = $features_query->offset($pages->offset)->limit($pages->limit)->asArray()->all(); return $this->render('types', ['metrics_list' => FeaturesMetrics::find()->asArray()->all(), 'features_types_model' => $features_types_model, 'features_list' => $features_list, 'current_mode' => $current_mode, 'features_synonims' => FeaturesSynonims::getUnsorted(), 'pages' => $pages]); }
public function testFirstLastPageLabels() { $pagination = new Pagination(); $pagination->setPage(5); $pagination->totalCount = 500; $pagination->route = 'test'; $output = LinkPager::widget(['pagination' => $pagination, 'firstPageLabel' => true, 'lastPageLabel' => true]); static::assertContains('<li class="first"><a href="/?r=test&page=1" data-page="0">1</a></li>', $output); static::assertContains('<li class="last"><a href="/?r=test&page=25" data-page="24">25</a></li>', $output); $output = LinkPager::widget(['pagination' => $pagination, 'firstPageLabel' => 'First', 'lastPageLabel' => 'Last']); static::assertContains('<li class="first"><a href="/?r=test&page=1" data-page="0">First</a></li>', $output); static::assertContains('<li class="last"><a href="/?r=test&page=25" data-page="24">Last</a></li>', $output); $output = LinkPager::widget(['pagination' => $pagination, 'firstPageLabel' => false, 'lastPageLabel' => false]); static::assertNotContains('<li class="first">', $output); static::assertNotContains('<li class="last">', $output); }
/** * Lists all Song models. * @param $song_kingdom_id * @return mixed */ public function actionIndex($song_kingdom_id) { $query = Song::find()->andWhere(['created_by' => Yii::$app->getUser()->getId(), 'song_kingdom_id' => $song_kingdom_id]); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(10); $models = $query->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('songIndex', ['models' => $models, 'pages' => $pages]); // $dataProvider = new ActiveDataProvider([ // 'query' => Song::find(), // ]); // // return $this->render('index', [ // 'dataProvider' => $dataProvider, // ]); }
/** * Lists all Album models. * @return mixed */ public function actionIndex() { $query = Album::find(); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(10); $models = $query->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('albumIndex', ['models' => $models, 'pages' => $pages]); // $dataProvider = new ActiveDataProvider([ // 'query' => Album::find(), // ]); // // return $this->render('index', [ // 'dataProvider' => $dataProvider, // ]); }
public function actionIndex() { $query = Topic::find()->joinWith('topicContent')->joinWith('user')->orderBy('topic_date_add DESC'); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $page = 1; if (isset($_GET["page"])) { $page = $_GET["page"]; } $limit = 10; $offset = $limit * ($page - 1); $pageSize = ceil($countQuery->count() / $limit); $pages->setPageSize($pageSize); $models = $query->offset($offset)->limit($limit)->all(); return $this->render('index', ['models' => $models, 'pages' => $pages]); }
public function actionGetTopics() { $query = Topic::find()->where(['active' => 1])->with('tags'); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count(), 'defaultPageSize' => 3]); $cacheTopics = 'Topics' . $pages->getPage(); if (Yii::$app->request->get('cache')) { Yii::$app->cache->delete($cacheTopics); } if (false === ($topics = Yii::$app->cache->get($cacheTopics))) { if (null === ($topics = $query->offset($pages->offset)->limit($pages->limit)->all())) { throw new NotFoundHttpException(); } Yii::$app->cache->set($cacheTopics, $topics, 86400, new TagDependency(['tags' => []])); } $this->renderJSON($topics); }
public function actionCategory() { $category_id = Yii::$app->request->get('category'); if (is_null($category_id)) { return $this->actionIndex(); } $query = TblBlog::find()->where(['category_id' => $category_id]); $page = clone $query; $pages = new Pagination(['totalCount' => $query->count()]); $pages->setPageSize(5); $articles = $query->offset($pages->offset)->limit($pages->limit)->asArray()->all(); foreach ($articles as $key => $value) { $articles[$key]['text'] = mb_substr($value['text'], 0, 100, 'UTF-8'); } $category = TblCategory::find()->where(['id' => $category_id])->asArray()->one(); return $this->render('category', ['articles' => $articles, 'category' => $category, 'pages' => $pages]); }
/** * Lists all Photo models. * @return mixed */ public function actionIndex($album_id) { $albumModel = Album::findOne($album_id); $query = Photo::find()->andWhere(['album_id' => $album_id]); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(10); $models = $query->offset($pages->offset)->limit($pages->limit)->all(); return $this->render('photoIndex', ['models' => $models, 'pages' => $pages, 'userCreadedBy' => User::find()->andWhere(['id' => $albumModel->created_by])->asArray()->one(), 'userExtendCreadedBy' => UserExtend::find()->andWhere(['user_id' => $albumModel->created_by])->asArray()->one()]); // $dataProvider = new ActiveDataProvider([ // 'query' => Photo::find(), // ]); // // return $this->render('index', [ // 'dataProvider' => $dataProvider, // ]); }
public function createUrl($page, $pageSize = null, $absolute = false) { $url = parent::createUrl($page, $pageSize, $absolute); if (!$absolute) { return \Yii::$app->params['static_host'] . '/' . ltrim($url, '/'); } else { return $url; } }
public function actionIndex() { $query = Users::find()->leftJoin('media', array('id' => 'user_id'))->where(['type' => 1, 'active' => 1]); $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); echo $pages; die; $page = 1; if (isset($_REQUEST["page"])) { $page = intVal($_REQUEST["page"]); } $limit = 12; $offset = $limit * ($page - 1); $pageSize = ceil($countQuery->count() / $limit); $pages->setPageSize($pageSize); $models = $query->offset($offset)->limit($limit)->all(); $city = City::find()->all(); return $this->render('index', ['models' => $models, 'pages' => $pages, 'city' => $city]); }
public function setPagination($value) { if (is_array($value)) { $config = ['class' => Pagination::className(), 'pageSizeParam' => 'pageSize']; $this->_pagination = Yii::createObject(array_merge($config, $value)); } elseif ($value instanceof Pagination || $value === false) { $this->_pagination = $value; } else { throw new InvalidParamException('Only Pagination instance, configuration array or false is allowed.'); } }
protected static function getDataProvider($method, $datasetName, $options = array(), Pagination $pagination = null) { $tag = null; if (isset($options['tag'])) { $tag = $options['tag']; unset($options['tag']); } if (!$pagination && $pagination !== false) { $pagination = new Pagination(); $result = self::getWhmcs()->call($method, $options, $tag); $pagination->totalCount = $result->totalresults; } if ($pagination !== false) { $options = array_merge($options, ['limitstart' => $pagination->getOffset(), 'limitnum' => $pagination->getLimit()]); } if ($result = self::getWhmcs()->call($method, $options, $tag)) { return new Provider(['response' => $result, 'datasetName' => $datasetName, 'pagination' => $pagination]); } return null; }
public function actionFind($propert = '', $price = '', $apartment = '') { $this->layout = 'sell'; $query = Advert::find(); $query->filterWhere(['like', 'address', $propert])->orFilterWhere(['like', 'description', $propert])->andFilterWhere(['type' => $apartment]); if ($price) { $prices = explode("-", $price); if (isset($prices[0]) && isset($prices[1])) { $query->andWhere(['between', 'price', $prices[0], $prices[1]]); } else { $query->andWhere(['>=', 'price', $prices[0]]); } } $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->setPageSize(10); $model = $query->offset($pages->offset)->limit($pages->limit)->all(); $request = \Yii::$app->request; return $this->render("find", ['model' => $model, 'pages' => $pages, 'request' => $request]); }
/** * Список заявок. * * @return string */ public function actionIndex() { /** @var \common\models\User $user */ $user = Yii::$app->getUser()->getIdentity(); $query = Lead::find()->where(['company_id' => $user->getCompanyId(), 'is_deleted' => false]); if ($selectedLandingId = Yii::$app->getSession()->get('selected_landing_id')) { $query->andWhere(['landing_id' => $selectedLandingId]); } if ($selectedLeadStatus = Yii::$app->getSession()->get('selected_lead_status')) { $query->andWhere(['status' => $selectedLeadStatus]); } $countQuery = clone $query; $pagination = new Pagination(['totalCount' => $countQuery->count()]); $pagination->setPageSize(LeadHelper::SHOW_LEAD_PER_PAGE); $leads = $query->offset($pagination->offset)->limit($pagination->limit)->orderBy(['lead_id' => SORT_DESC])->all(); $landingNames = (new LandingComponent())->getActiveLandingNamesByCompanyId($user->getCompanyId()); if (empty($landingNames)) { Yii::$app->getSession()->setFlash('warning', sprintf('Не возможно добавлять заявки, так как не было создано ни одной промо-страницы! <a href="%s">Добавить промо-страницу.</a>', Url::to('/landing/add'))); } return $this->render('index', ['user' => $user, 'leads' => $leads, 'pagination' => $pagination, 'landingNames' => $landingNames, 'selectedLandingId' => $selectedLandingId, 'selectedLeadStatus' => $selectedLeadStatus]); }
/** * @inheritdoc */ public function bootstrap($app) { if ($app instanceof \yii\web\Application && ($i18nModule = Yii::$app->getModule('i18n'))) { $moduleId = $i18nModule->id; $app->getUrlManager()->addRules(['translations/<id:\\d+>' => $moduleId . '/default/update', 'translations/page/<page:\\d+>' => $moduleId . '/default/index', 'translations/index' => $moduleId . '/default/index'], false); Yii::$container->set(Pagination::className(), ['pageSizeLimit' => [1, 100], 'defaultPageSize' => $i18nModule->pageSize]); } if ($app instanceof \yii\console\Application) { if (!isset($app->controllerMap['i18n'])) { $app->controllerMap['i18n'] = I18nController::className(); } } }
/** * List all topics */ public function actionIndex() { $pageNo = Yii::$app->request->get("page", 0) - 1; $sectionId = Yii::$app->request->get("sectionId", Yii::$app->request->post("sectionId", '')); $sectionList = $this->getSectionList(); $query = Topic::find(); if ($sectionId) { $query->andFilterWhere(['SectionId' => $sectionId]); } // config pagination properties $countQuery = clone $query; $pages = new Pagination(['totalCount' => $countQuery->count()]); $pages->pageSize = Yii::$app->getModule('helpsystem')->getModule('admin')->topicPageLimit; $pages->params = ["sectionId" => $sectionId]; $offset = $pages->pageSize * $pageNo; if ($countQuery->count() < $offset) { $offset = floor($countQuery->count() / $pages->pageSize) + 1; } $topicList = $query->offset($offset)->limit($pages->pageSize)->orderBy('Order ASC')->all(); $pages->setPage($pageNo); return $this->render("index", ['topicList' => $topicList, 'sectionList' => $sectionList, 'sectionId' => $sectionId, 'pages' => $pages, 'pageNo' => $pageNo + 1]); }
/** * 获取店铺详情 */ private static function getStoreBrief() { $brief = ['userMobile', 'storeId', 'logo', 'storeName', 'enterpriseType', 'createTime', 'address']; $sql = 'SELECT ' . implode(',', $brief) . ' FROM store AS s INNER JOIN user as u ON(s.userId=u.userId)'; if (static::$storeId) { $sql .= ' WHERE s.storeId=' . static::$storeId; } else { $total = static::getDb()->createCommand($sql)->query()->count(); $data['pagination'] = $pagination = new Pagination(['totalCount' => $total, 'pageSize' => static::$pageSize]); $sql .= ' LIMIT ' . $pagination->getOffset() . ',' . $pagination->getLimit(); } $data['data'] = static::getDb()->createCommand($sql)->queryAll(); $sale = StoreSale::getStoreSale(); foreach ($data['data'] as &$v) { foreach ($sale as $vs) { if ($v['storeId'] == $vs['storeId']) { $v['username'] = $vs['username']; } } } return $data; }
public function testValidatePage() { $pagination = new Pagination(); $pagination->validatePage = true; $pagination->pageSize = 10; $pagination->totalCount = 100; $pagination->setPage(999, true); $this->assertEquals(9, $pagination->getPage()); $pagination->setPage(999, false); $this->assertEquals(999, $pagination->getPage()); }