alexaandrov
4/5/2016 - 2:44 PM

Display information of many to many relation tables in view

Display information of many to many relation tables in view

// Create method in your model class
public function getManyToManyTableName($relationName)
{
    $string = '';
    $array = $this->$relationName;
    if(empty($array)) {
        return Yii::t('app', 'Not set');
    }
    $arrayLength = count($array);
    $counter = 0;
    foreach ($array as $item) {
        if (++$counter == $arrayLength) {
            $string .= Yii::t('app', $item->name);
        } else {
            $string .= Yii::t('app', $item->name) . ", ";
        }
    }
    return $string;
}

// In your view, paste this code in the attributes in GridView
<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
      // 'id',
      // ...
      [
        'attribute' => 'posts', // Write here your table relation name, sample: post_ids or posts, book_ids or books
        'label' => Yii::t('app', 'Posts'),
        'value' =>  $model->getManyToManyTableName('posts', $model), // Write here your table relation name, and $model
      ],                                                             // sample: post_ids or posts, book_ids or books
    ],
])?>