Last active
April 9, 2016 11:18
-
-
Save alexaandrov/2a4eb82675e28bb52292de825e51859c to your computer and use it in GitHub Desktop.
Display information of many to many relation tables in view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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