7

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 ?

Andy K
  • 4,944
  • 10
  • 53
  • 82
sudo_ee_
  • 109
  • 5
  • 15

3 Answers3

8

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')),
},
soju
  • 25,111
  • 3
  • 68
  • 70
0

Try with:

<?= DetailView::widget([
        'model' => $model,
        'attributes' => [

         [
              'header' => 'number of hobbies',
              'value' => function($data) {
                       return $data->getTblDataHobis()->count();
              }
          ]

    ]) ?>
Fabrizio Caldarelli
  • 2,982
  • 11
  • 14
0

Just get the item data, and after that create a simple yii2 query. For example my 'worker' has city id, with this id we can find city name by this id.

     <?= DetailView::widget([
        'model' => $model,
        'attributes' => [
            'id',
            'name:ntext',
            'surname:ntext',
            'fathers',
            [
                'attribute' => 'city_id',
                'value'=> function($data){
                    $city = City::find()->where(['id'=>$data->city_id])->one();
                    $info = $city->name;
                    return $info;
                },
                'format'=>'html',
            ],
            'status',
            'street',
            'in_company',
        ],
    ]) ?>