S
S
Skrolea2016-04-18 13:51:03
Yii
Skrolea, 2016-04-18 13:51:03

How to display posts by time?

Good afternoon.
There are photos in the database broken down by years
(Id: 1; url: photo1 ; year : 2015)
Standard controller

public function actionIndex() {
        $searchModel = new ArchiveSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

And I twist
foreach ($dataProvider->models as $model) {
    ?>
    <div class="panel panel-default">
        <div class="panel-heading"><?= $model->year; ?></div>
        <div class="panel-body">
            <div class="row">
                <div class="col-xs-6 col-md-3">
                    <div class="thumbnail-journal thumbnail">
                        <img src="/<?= $model->cover_url; ?>" alt="<?= Yii::t('app', '_Journal') ?>">
                        <a href="<?= Url::to(['view']) ?>" class="btn btn-primary" role="button"><span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span> <?= Yii::t('app', '_View') ?></a>  
                        <a href="/<?= $model->journal_url; ?>" download="/<?= $model->journal_url; ?>" class="btn btn-default pull-right" role="button"><span class="glyphicon glyphicon-download" aria-hidden="true"></span> <?= Yii::t('app', '_Download') ?></a>
                    </div>
                </div>             
            </div>
        </div>
    </div>
    <?php
}

Is it possible to display "Year - 2015, post 1, post2, ... postN", "Year - 2016, post1, post2, postN" using foreach in the view or do I need to make queries to the database, splitting by years?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Elena Stepanova, 2016-04-18
@Skrolea

firstly, if you need data not for gridview\listview, there is no need to return dataProvider in the ArchiveSearch model, it is enough to return $query->all();
and to get by years - first group the array of results by years

$result = [];
         $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
         foreach($dataProvider->models as $model){
              $result[$model->year][] = $model;
         }
         return $this->render('index', [
                    'searchModel' => $searchModel,
                    'result' => $result,
        ]);

<?php foreach($result as $year=>$models):?>
     <h3><?=$year?></h3>
    <?php foreach($models as $model):?>
          <?=$model->data?>
     <?php endforeach?>
<?php endforeach?>

A
Anton, 2016-04-18
@karminski

Try using grouping via ArrayHelper::map(inputArray, key, value, groupBy)
www.yiiframework.com/doc-2.0/guide-helper-array.ht...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question