Skip to content

Instantly share code, notes, and snippets.

@alexaandrov
Last active April 9, 2016 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexaandrov/2a4eb82675e28bb52292de825e51859c to your computer and use it in GitHub Desktop.
Save alexaandrov/2a4eb82675e28bb52292de825e51859c to your computer and use it in GitHub Desktop.
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
],
])?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment