Get relational data with CListView

Hi All,

I am trying to use a CListView to display data from a table in my database, however when I come to access relational data (such as $data->type->Name), I get the error: Trying to get property of non-object.

I have used the same syntax elsewhere, so I know the database is OK, just having issues with this widget!

The following is how the widget is created:

$this->widget(‘zii.widgets.CListView’, array(



)); ?>

If you need any other info, I’ll be happy to dump it in :)



Provide your type relation

Urgh, made a bit of a mess up there; my relations had a 0 at the end!!

Thanks anyway :)

OK, but in my case the relation looks not messy:

'head' => array(self::HAS_ONE, 'Employee', 'id')

So I wand to use the relation within a CListView with this statement:

echo CHtml::encode($data->head->lastName);

During that I always get this annoying error "Trying to get property of non-object"

Any hint’s what I can do to prevent this?



You don’t give a hint about the context of your query but my first guess is that you should use a BELONGS_TO realtionship instead.

Also make sure there is an object returned for head before accessing it.


Aaaargh, that’s it! I had some “holes” in my data, some records didn’t had the heads-id set. For these records the relation form Department to Employee was not defined. So I did:

if (!empty($data->head))

  echo CHtml::encode($data->head->lastName);


  echo 'n.n.';

Now it works like a charm!!!

thanks a lot


How about :

echo CHtml::encode($data->head['lastName']);

… works also, and is 3 lines shorter :slight_smile: