Tuesday, February 15, 2022

[FIXED] Yii2 list items inside a categories

Issue

My controller

public function actionIndex()
{
    $query = Documents::find();
    $docs = $query->orderBy('cate_id ASC')->all();
    return $this->render('index', [
        'docs' => $docs,
    ]);
}

My view

<?php foreach ($docs as $doc) {  
$cate = app\models\Categories::find()->where(['id'=>$doc->cate_id])->one();?>
    <h4><?=$cate->title?></h4>
    <p><?= Html::a($doc->title, ['documents/view', 'id'=>$doc->id]) ?></p>

<?php } ?>

With this my view look like

Category 1

  • Menu Item Title 1

Category 1

  • Menu Item Title 2

Category 2

  • Menu Item Title 3

I want it to display

Categories 1

  • Menu Item Title 1
  • Menu Item Title 2

Categories 2

  • Menu Item Title 3

Please help me with this.

Thank you!


Solution

For your task, use Yii ArrayHelper to solve this problem very easily.

Check this link http://www.yiiframework.com/doc-2.0/guide-helper-array.html

You can group the records according to a specific key/column by using ArrayHelper::index method.

In your case, you have to group the records with 'cate_id' (which refers your category id).

   //dont forget to import ArrayHelper before using it. 
   //use \yii\helpers\ArrayHelper.
   $catList = ArrayHelper::index($docs, null, 'cate_id');

Above code will produce grouped array. example....

   [
        1 =>[
              ['Menu Item Title 1','other column data','....'],
              ['Menu Item Title 2','other column data','....']
        ],
        2 =>[
              ['Menu Item Title 3','other column data','....'],
              ['Menu Item Title 4','other column data','....']
        ]

   ]

Now you iterate through this array/array object.

     <?php
     foreach($catList as $cate_id => $catItems)
     {
        $cate = app\models\Categories::find()->where(['id'=>$cate_id])->one();
        echo '<h4>'.$cate->title.'</h4>';
        foreach($catItems as $catItem)
        {

           echo '<p>'.Html::a($catItem['title'], ['documents/view', 'id'=>$catItem['id']]).'</p>';
        }

     }
     ?>

After getting some grip on Yii code, try to code in Yii way. That is, in this case, do not write queries in View.

You can use model relation to get the name of the category.



Answered By - Hearaman

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.