Hello,
Im using Yii2 and i want to display only the 20 last recents records in GridView (each record has the "date" field). I want just to display the 20 last items of the table even if the table has more than 100 records.
Please i need your help.
Hello,
Im using Yii2 and i want to display only the 20 last recents records in GridView (each record has the "date" field). I want just to display the 20 last items of the table even if the table has more than 100 records.
Please i need your help.
Use ArrayDataProvider.
If your primary key is "id":
$models = MyModel::find()->where(...)->orderBy('id DESC')->limit(20).
$dataProvider = new \yii\data\ArrayDataProvider(['models' => $models]);
Thks for the feedback.
That is my code:
"//$query = Tabnews::find();
$query = Tabnews::find()->orderBy('dat_date DESC')->limit(20);
$dataProvider = new \yii\data\ArrayDataProvider(['models' => $query]);
/*$dataProvider = new ArrayDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['dat_date'=>SORT_DESC]],
]);*/
$this->load($params);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
return $dataProvider;
}
$query->andFilterWhere([
'int_id' => $this->int_id,
'dat_date' => $this->dat_date,
'int_author' => $this->int_author,
'lab_photo' => $this->lab_photo,
]);
$query->andFilterWhere(['like', 'lab_title', $this->lab_title])
->andFilterWhere(['like', 'lab_contain', $this->lab_contain]);
return $dataProvider;"
i want to display the last 20 news published. It gives an error
"array_keys() expects parameter 1 to be array, object given".
i do not know what is the problem.
I’m sorry, I’ve missed in my code ->all() at the end of $models var.
So this should be your working code:
$this->load($params);
$query = Tabnews::find()->where($model->attributes)->orderBy('dat_date DESC')->limit(20);
if (!$this->validate()) {
// uncomment the following line if you do not want to return any records when validation fails
// $query->where('0=1');
$models = $query->all();
$dataProvider = new \yii\data\ArrayDataProvider(['models' => $models]);
return $dataProvider;
}
$query->andFilterWhere([
'int_id' => $this->int_id,
'dat_date' => $this->dat_date,
'int_author' => $this->int_author,
'lab_photo' => $this->lab_photo,
]);
$query->andFilterWhere(['like', 'lab_title', $this->lab_title])
->andFilterWhere(['like', 'lab_contain', $this->lab_contain]);
$models = $query->all();
$dataProvider = new \yii\data\ArrayDataProvider(['models' => $models]);
return $dataProvider;
Thks for your help,
it is working very well.
BR
set pagination to false, then set limit
public function actionIndex()
{
$searchModel = new SetoranSearchModel();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$dataProvider->pagination = false;
$dataProvider->query->limit(5);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}