简体   繁体   中英

Check if relation isset with value attribute of CDataColumn

I am aware that one can use a form of conditional statement inside the value attribute of CDataColumn, as outlined in the question conditional statements inside of 'value' for CDataColumn. I was wondering if there is a way to check if a model actually has a value set before trying to display it. My problem arises as my model Source has an optional relation 'country' that is not neccessarily set for all instances of Source. So when I access the country name in a Source CDataColumn, I get the PHP

Trying to get property of non-object

.. if any of the Sources in that grid do not have their country set. I

s there any way to check if the relation is set inside the 'value' attribute of the column?

You should try this (you should replace name with the needed attribute) :

array(
  'name'=>'country',
  'value'=>'(isset($data->country)) ? $data->country->name : ""',
),

You could also use a getter in your Source model, eg :

public function getCountryName()
{
  // I assume country_id is the foreign key
  if (isset($this->country_id) && isset($this->country))
    return $this->country->name;

  return '';
}

And with this getter, you just need to add this to your gridview columns :

  'countryName',

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM