Reputation: 39
In brief, I have a table machines, which has a FK pointing to SubCategory.id The relation is correctly setup by Gii. However, the FK column in Machine can be set to NULL as the Action field is not compulsory.
[
'attribute'=>'machine Sub-category',
'value' => function ($model) {
return $model->subCategory->subcat_name;
},
],
Above code displays the subcategory name when FK is not NULL. But if FK is NULL, then I get PHP error:
Trying to get property of non-object
I understand that error is because of NULL value. ( Because I don't get this error if I add some value instead of NULL)
So my query is - for a FK column that may have NULL values, how do I get them to display in GridView or Detailview?
Upvotes: 1
Views: 860
Reputation: 133400
you can check if the subcategory is null
[
'attribute'=>'machine Sub-category',
'value' => function ($model) {
if (isset($model->subCategory)){
return $model->subCategory->subcat_name;
} else {
return '';
}
},
],
Upvotes: 2