How to create pager in Yii2? - php

I was searching how to create pager in Yii2 using LinkPage widget.
Is there any example? I am new in Yii, so any help would be good.

It is simple
$dataProvider = new ActiveDataProvider([
'query' => User::find(),
'pagination' => array('pageSize' => 50),
]);
echo \yii\widgets\LinkPager::widget([
'pagination'=>$dataProvider->pagination,
]);
Or if you don't use dataProvider you should use this:
$query = User::find();
$pagination = new Pagination(['totalCount' => $query->count(), 'pageSize'=>30]);
echo \yii\widgets\LinkPager::widget([
'pagination' => $pagination,
]);

In controller:
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,
]);
}
In view file:
foreach ($models as $model) {
// display $model here
}
// display pagination
echo LinkPager::widget([
'pagination' => $pages,
]);

Below is too simple for adding pagination,
We just need to add in controller,
$dataProvider = new ActiveDataProvider([
'query' => Post::find(),
'pagination' => [
'pageSize' => 20,
],
]);
Yii2 will bring pagination on index page,
https://yii2-framework.readthedocs.io/en/stable/guide/output-data-widgets/

In your controller
$searchModel = new CourseModuleMasterSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination = ['pageSize' => 20];//add this line

Related

How do I display pagination in Yii2 GridView?

I am getting my dataProvider from which I try to remove some models that don't meet the wanted criteria. This filter is not SQL related and therefore I can't apply it directly to the query. On my view the pagination links are displayed if I leave the dataprovider just as it was. But after I apply the filters to remove the unwanted models, the pagination links disappear. I have tried setting the pagination on my new dataProvider but nothing works.
Here's my code in the controller action:
$request = Yii::$app->request;
$search_model = new StaffEmploymentListViewSearch();
$data_provider = $search_model->search($request->queryParams);
$models = $data_provider->models;
for($k=0;$k<count($models);$k++)
{
if($models[$k]->employ === null){
unset($models[$k]);
}
}
$config = [
'pageParam' => 'page',
'pageSizeParam' => 'per-page',
'forcePageParam' => true,
'route' => null,
'params' => null,
'urlManager' => null,
'validatePage' => true,
'totalCount' => 5214,
'defaultPageSize' => 20,
'pageSizeLimit' => [
'0' => 1,
'1' => 50
],
'pagesize' => 20
];
$data_provider->setModels($models);
$data_provider->setPagination($config);
return $this->render('all-staff',[
'dataProvider' => $data_provider,
'searchModel' => $search_model
]);
Here's my search method:
$query = StaffEmploymentListView::find()
->SELECT([
'PAYROLL_NO',
'BIRTH_DATE',
"ADD_MONTHS(BIRTH_DATE, 70 * 12) AS RETIRE_DATE"
]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => false,
'pagination' => [
'pagesize' => 20,
],
]);
How do I go about doing this?
Try to use ArrayDataProvider
$query = StaffEmploymentListView::find()
->select([
'PAYROLL_NO',
'BIRTH_DATE',
"ADD_MONTHS(BIRTH_DATE, 70 * 12) AS RETIRE_DATE"
]);
$allModels = [];
foreach ($query->all as $staffEmployment)
{
if ($model->employ === null){
$allModels[] = $model;
}
}
$dataProvider = new ArrayDataProvider([
'allModels' => $allModels,
'pagination' => [
'pageSize' => 20,
],
'sort' => false
]);
return $this->render('all-staff',[
'dataProvider' => $data_provider,
'searchModel' => $search_model // ???
]);

how to create pagination for my model index page pagination at limit 15

My pagination does not show on my index page.
Can someone tell me how to create pagination for my index page with a limit of 15?
public function actionIndex()
{
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$pagination = new Pagination([
'defaultPageSize' => 5,
'totalCount' =>$this->count(),
]);
$employee = $query->orderBy('name')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'Employee-create' => $employee,
'pagination' => $pagination,
]);
}
You can set pageSize for data provider this way
$searchModel = new EmployeeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination->pageSize=15;
In you file EmployeeSearch.php include the param pagination
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 15,
],
]);

Main Search Form in Yii2

I'm really new in Yii2 and I still don't know how to configure it properly. I noticed that the GridView has search fields on each column. What I need now is to create a main/single search field wherein a user can input keywords then results will show in the GridView after hitting the search button.
Is this possible? I also used this Kartik widget in my search form field which has a dropdown list in it. Image here.
We're told to use this dropdown search and when the user inputs some keywords (sometimes returns 'No results found' on the dropdown list), and clicks the Search button, the page will refresh displaying all the results based on the keywords inputted.
I also searched some problems same as mine here in SO, such as these:
Yii2 Search model without using GridView
yii 2 , make an active form text field master search field
I found no luck. The second link doesn't have any answers.
I will include my action controller here in case you need it.
public function actionIndex()
{
$session = Yii::$app->session;
$searchModel = new PayslipTemplateSearch();
$PayslipEmailConfig = PayslipEmailConfig::find()->where(['company_id'=> new \MongoId($session['company_id'])])->one();
$payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
$payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();
$pTemplateModel = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->all();
$user = User::find()->where(['_id' => new \MongoId($session['user_id'])])->one();
$module_access = explode(',', $user->module_access);
$dataProvider = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
return $this->render('index', [
'PayslipEmailConfig' => $PayslipEmailConfig,
'dataProvider' => $dataProvider,
'payslipTemplateA' => $payslipTemplateA,
'payslipTemplateB' => $payslipTemplateB,
]);
}
My view, index.php
<?php
$users = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
echo $this->render('_search', ['model' => new User(), 'users' => $users]);
?>
_search.php
<?php $form = ActiveForm::begin([
'action' => ['searchresults'],
'method' => 'get',
'id' => 'searchForm'
]); ?>
<?php
$listData = array();
foreach ($users as $user) {
$listData[(string)$user->_id] = $user->employeeId. ' '.$user->fname.' '.$user->lname;
}
echo $form->field($model, '_id')->widget(Select2::classname(), [
'data' => $listData,
'addon' => [
'append' => [
'content' => Html::button('Search', ['class'=>'btn btn-primary']),
'asButton' => true
]
],
'options' => [ 'class' => 'dropdown-responsive', 'responsive' => true, 'placeholder' => 'Search employee ID or name (e.g. 10015 or John Cruz)', 'id' => 'user_id', 'name' => 'id'],
'pluginOptions' => [
'allowClear' => true,
'responsive' => true
],
]);
?>
<?php ActiveForm::end(); ?>
Really need help for this one.
This example code as per your requirement. so, try it.
User Searchmodel's search() method.
public function search($params)
{
$query = User::find();
$query->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
......
........
}
Controller's actionIndex
public function actionIndex()
{
$session = Yii::$app->session;
/* $searchModel = new PayslipTemplateSearch(); */
$PayslipEmailConfig = PayslipEmailConfig::find()->where(['company_id'=> new \MongoId($session['company_id'])])->one();
$payslipTemplateA = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'A'])->one();
$payslipTemplateB = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->andwhere(['template_name' => 'B'])->one();
$pTemplateModel = PayslipTemplate::find()->where(['company_id' => new \MongoId($session['company_id'])])->all();
$user = User::find()->where(['_id' => new \MongoId($session['user_id'])])->one();
$module_access = explode(',', $user->module_access);
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
/*
$dataProvider = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
*/
return $this->render('index', [
'PayslipEmailConfig' => $PayslipEmailConfig,
'dataProvider' => $dataProvider,
'payslipTemplateA' => $payslipTemplateA,
'payslipTemplateB' => $payslipTemplateB,
'searchModel' => $searchModel,
]);
}
and index.php
<?php
$users = User::find()->where(['user_type' => 'BizStaff'])->andwhere(['parent' => new \MongoId($session['company_owner'])])->all();
echo $this->render('_search', ['model' => $searchModel, 'users' => $users]);
?>

Yii2 Listview how to display data in view

Greetings
I want to display data from my Atividades model in Yii2
My AtividadesController has the following code for actionView2
public function actionView2()
{
$query = new Query;
$dataProvider = new ActiveDataProvider([
'query' => $query->from('Atividades'),
'pagination' => [
'pageSize' => 20,
],
]);
// get the posts in the current page
$posts = $dataProvider->getModels();
return $this->render('view2', ['dataProvider' => $dataProvider, 'posts' => $posts]);
}
And in my View 2 i have the following List View that appears with the message showing 4 of 4 items, but doesn't shows the items
<?= ListView::widget([
'dataProvider' => $dataProvider,
]); ?>
In Y1.xx i had a property called 'attributes' for display the model fields
How can i display the model fileds in Yii2 inside this Listview
Many thanks in advance
I have solved it by myself :)
It was not hard
In my View2 Written the following code
<?= ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_view2',
]); ?>
And then duplicated an original view file, changed its name to _view2, put it in the same folder, and style it has needed
In my ActividadesController changed the actionView2 code to:
public function actionView2()
{
$dataProvider = new ActiveDataProvider([
'query' => Atividades::find(),
'pagination' => [
'pageSize' => 20,
],
]);
// get the posts in the current page
$posts = $dataProvider->getModels();
return $this->render('view2', ['dataProvider' => $dataProvider]);
}
_View2 code
<?= DetailView::widget([
'model' => $model,
'attributes' => [
//'id',
'atividade',
'descricao:ntext',
//'ativo',
],
]) ?>
SOLVED

Yii2 data provider default sorting

In Yii 1.1 this code works for default sorting:
$dataProvider = new CActiveDataProvider('article',array(
'sort'=>array(
'defaultOrder'=>'id DESC',
),
));
How default sorting can be set in Yii2?
Tried below code, but no result:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder'=>'topic_order asc']
]);
I think there's proper solution. Configure the yii\data\Sort object:
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],
]);
Official doc link
Or
$dataProvider->setSort([
'defaultOrder' => ['topic_order'=>SORT_DESC],
'attributes' => [...
defaultOrder contain a array where key is a column name and value is a SORT_DESC or SORT_ASC that's why below code not working.
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder'=>'topic_order asc']
]);
Correct Way
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => [
'topic_order' => SORT_ASC,
]
],
]);
Note: If a query already specifies the orderBy clause, the new ordering instructions given by end users (through the sort configuration) will be appended to the existing orderBy clause. Any existing limit and offset clauses will be overwritten by the pagination request from end users (through the pagination configuration).
You can detail learn from
Yii2 Guide of Data Provider
Sorting By passing Sort object in query
$sort = new Sort([
'attributes' => [
'age',
'name' => [
'asc' => ['first_name' => SORT_ASC, 'last_name' => SORT_ASC],
'desc' => ['first_name' => SORT_DESC, 'last_name' => SORT_DESC],
'default' => SORT_DESC,
'label' => 'Name',
],
],
]);
$models = Article::find()
->where(['status' => 1])
->orderBy($sort->orders)
->all();
if you have CRUD (index) and you need set default sorting your controller for GridView, or ListView, or more...
Example
public function actionIndex()
{
$searchModel = new NewsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// set default sorting
$dataProvider->sort->defaultOrder = ['id' => SORT_DESC];
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
you need add
$dataProvider->sort->defaultOrder = ['id' => SORT_DESC];
Try to this one
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$sort = $dataProvider->getSort();
$sort->defaultOrder = ['id' => SORT_ASC];
$dataProvider->setSort($sort);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['iUserId'=>SORT_ASC]]
]);
As stated in the guide, you must specify the sorting behaviors of a data provider by configuring its sort properties which correspond to the configurations for yii\data\Sort
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['topic_order' => SORT_ASC]],
]);
$modelProduct = new Product();
$shop_id = (int)Yii::$app->user->identity->shop_id;
$queryProduct = $modelProduct->find()
->where(['product.shop_id' => $shop_id]);
$dataProviderProduct = new ActiveDataProvider([
'query' => $queryProduct,
'pagination' => [ 'pageSize' => 10 ],
'sort'=> ['defaultOrder' => ['id'=>SORT_DESC]]
]);
you can modify search model like this
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => [
'defaultOrder' => ['user_id ASC, document_id ASC']
]
]);

Categories