Search code examples
phplistviewyii2

Yii2 first and last items in the ListView


I have a typical ListView widget in a view as follows:

public function actionView($id)         
    {
        $model = $this->findModel($id);
        $dataProvider = new \yii\data\ActiveDataProvider(['query' => \app\models\Verses::find()->where(['sura_id' =>$id])->with('sura')]);          
        return $this->render('view', [
            'model' => $model,
            'dataProvider' => $dataProvider,
        ]);
    }

In the view a list of Verses model is rendered and the pager of the ListView is available too.

I want to add some details to the page title. Those details are data from the first and last records of the Verses model rendered in the list.

I have tried to use min() and max() PHP functions to get the first and the last records in the view as follows:

$min = min($model->verses);
echo $min->verse_id;

However, it returns the ultimate first record regarding-less the current pager page. In other words, it does not return the verse_id value of the first item of the list.

Is there any way to get the first, last or even a specific nth item of the ListView?


Solution

  • You should simply try :

    $models = $dataProvider->getModels();
    $first = reset($models);
    $last = end($models);
    

    Read more about reset and end.