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']
]
]);
Related
i have a search model where i need to get only active models (status 1) without deleted models (status 0) but it is showing all models including deleted ones
use yii\data\ActiveDataProvider;
public function search($params)
$query = Post::find()->where(['status' => 1]);
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'created_at' => SORT_DESC,
'title' => SORT_ASC,
]
],
]);
// returns an array of Post objects
$posts = $provider->getModels();
This code do not execute the first condition where(['status' => 1])
why?
I have a Listview in yii2 to display items, in this case the items are video thumbnails, and i want to display only 5, i tried to limit the query...
$dataProvider = new ActiveDataProvider([
'query' => Video::find()
->select(['video.*', 'COUNT(video_like.video_id) AS countlike'])
->joinWith(['likes'])
->groupBy(['video_like.video_id','video.video_id'])
->limit(5)
->orderBy(['countlike' => SORT_DESC])
]);
but it doesnt work...
my listview is:
<?php echo \yii\widgets\ListView::widget([
'dataProvider' => $dataProvider,
'pager' => [
'class' => \yii\bootstrap4\LinkPager::class,
],
'itemView' => '_video_item',
'layout' => '<div class="d-flex flex-wrap">{items}</div>{pager}',
'itemOptions' => [
'tag' => false,
],
]) ?>
Check this doc.
This should work for you:
$dataProvider = new ActiveDataProvider([
'query' => Video::find()
->select(['video.*', 'COUNT(video_like.video_id) AS countlike'])
->joinWith(['likes'])
->groupBy(['video_like.video_id','video.video_id'])
->orderBy(['countlike' => SORT_DESC]),
'pagination' => [
'pageSize' => 5,
]
]);
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 // ???
]);
I am using ArrayDataProvider and i want to know how to make the sort links in view like a
$sort->link('date')
in yii/data/Sort
Follow this (yii\data\sort) and this (yii\data\ArrayDataProvider) documentation
what you can do is make sort like this:
$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',
],
// or any other attribute
],
]);
after that you can put it in your array data provider
$query = new Query;
$provider = new ArrayDataProvider([
'allModels' => $query->from('post')->all(),
'sort' => $sort, // HERE is your $sort
'pagination' => [
'pageSize' => 10,
],
]);
// get the posts in the current page
$posts = $provider->getModels();
and finally in your view:
// any attribute you defined in your sort defination
echo $sort->link('name') . ' | ' . $sort->link('age');
I'm trying to display database for each user in descending date order using data provider this works for Yii 1 at controller :
$DataProvider = new CActiveDataProvider('ModelName', array(
'criteria' => array(
'condition' => 'user_id=' . Yii::app()->user->id,
'order' => 'submitted_dt DESC',
),
'pagination' => array(
'pageSize' => 20,
),
));
i try this in Yii 2 :
$DataProvider = new ActiveDataProvider([
'query' => ModelName::find(),
'criteria' => [
'condition' => 'user_id=' . Yii::$app->user->identity->id,
'order' => 'submitted_dt DESC',
],
'pagination' => [
'pageSize' => 20,
],
]);
// get posts in the current page
$Model= $DataProvider->getModels();
Error i get is unknown property: yii\data\ActiveDataProvider::criteria .So what is the way to set this condition and order ?
All suggestions are welcomed
The Yii2's right way would be:
$DataProvider = new ActiveDataProvider([
'query' => ModelName::find()->
where(['user_id'=>Yii::$app->user->identity->id])->
orderBy('submitted_dt DESC'),
'pagination' => [
'pageSize' => 20,
],
]);
// get posts in the current page
$Model= $DataProvider->getModels();
So, you don't need criteria in Yii2 as this is not exist anymore.