T
T
turkprogrammer2019-09-27 00:48:13
Yii
turkprogrammer, 2019-09-27 00:48:13

Implementation of YII2 pagination, to display elements of an array of images from a given folder, how to implement?

Hello everyone, I want to implement the output of images with pagination with a given number per page, the pagination helper does not work, I tried to convert an array into an object, it also does not work,

public function actionIndex() {
       $dir = 'uploads';   
       $query = \yii\helpers\FileHelper::findFiles($dir,['only'=>['*.jpg','*.png']]); // получаю массив картинок
     // dd($query );
       //echo ArrayHelper::isIndexed($files); //проверяю тип массива
       //echo gettype($query ); //массив
       $pages = new Pagination([
            'totalCount' => $query->count(),    //        count() - не работает, если задать в ручную тоже Call to a member function offset() on array
            'pageSize' => Yii::$app->params['pageSize'],
            'forcePageParam' => false,
            'pageSizeParam' => false
        ]);
        $files = $query->offset($pages->offset) //Call to a member function offset() on array
            ->limit($pages->limit)
            ->asArray()
            ->all();
    
       return $this->render('index', compact('files','pages'));
      
    }

How to implement pagination for array elements, i.e. pictures? Thanks in advance if there is a solution

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
turkprogrammer, 2019-09-27
@turkprogrammer

In general, I myself solved this problem with a minimum of code, this is the use of Class yii\data\ArrayDataProvider
Controller:

public function actionIndex() {
        $dir = 'uploads';

        $query = \yii\helpers\FileHelper::findFiles($dir, ['only' => ['*.jpg', '*.png']]);
        $data = $query;

        $provider = new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 12,
            ],
                /* 'sort' => [
                  'attributes' => ['id', 'name'],
                  ], */
        ]);

// получает строки для текущей запрошенной странице
        $files = $provider->getModels();      
        return $this->render('index', compact('files','provider'));
    }

view:
echo yii\grid\GridView::widget([
                'dataProvider' => $provider,
            ]);

This solution, if there is a need to display pictures or a list of files from a directory, can be useful to someone!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question