Rachna
Rachna

Reputation: 39

YII2 - Handle NULL value in gridView- Display a column of foreign keys where some may be NULL

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

Answers (1)

ScaisEdge
ScaisEdge

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

Related Questions