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
....
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 ?
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')),
},