Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show has many relation record in Yii2 GridView and DetailView?

I want to show staff has many hobbies from table hobbies in detail view and gridview.

But I got an error exception Trying to get property of non-object

Here's my schema code model:

app\model\TblDataStaff

enter image description here

    ....
        public function getTblDataHobis()
            {
                return $this->hasMany(TblDataHobies::className(), ['id_staff' => 'id']);
            }

view code: view.

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [
...
['attribute'=>'namHob','value'=>$model->tblDataHobis->id],
...
],
    ]) ?>

index:

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        //'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
......
['attribute'=>'namHob','value'=>function($namHob){return $namHob->tblDataHobis->name_hobby;},],
.....
['class' => 'yii\grid\ActionColumn'],
        ],]);?>

How to show many hobbies of staff ?

like image 438
sudo_ee_ Avatar asked Mar 25 '16 15:03

sudo_ee_


1 Answers

Nothing strange, you have a Trying to get property of non-object error simply because $model->tblDataHobis return an array of TblDataHobies objects.

You could simply try this :

// display hobbies names separated with commas
echo implode(', ', \yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby'));

For DetailView :

'value' => implode(\yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby')),

For GridView :

'value' => function($model) {
    return implode(\yii\helpers\ArrayHelper::map($model->tblDataHobis, 'id', 'name_hobby')),
},
like image 92
soju Avatar answered Sep 21 '22 01:09

soju