"Trying to get property of non-object" error

I’m pulling out my almost non-existant hair!

Example:

I have two tables:

Dog

  • id (primary)

  • name

  • vetid (a foreign key to the vet table)

Vet

  • id

  • practicename

So, I have a foreign key set up in the DOG model that is BELONG_TO the vet table.

If vetid is defined, I can appropriately display the vet’s practicename

However, if I have vetid NULL (let’s say the dog doesn’t have a vet yet), I will get the following error:

"Trying to get property of non-object" when trying to display practicename.

So… in my view, when I go: <?php echo $model->dogVet->practicename ?> what am I supposed to do if they did not select a vet (and I want to allow them to NOT select a vet)?

Should this NOT be a BELONG_TO foreign key? Each dog will may have 0 or 1 vet.

Any ideas would be appreciated.

Thanks!

Chris

Maybe code like this can solve it…


<?php echo isset($model->dogVet)?$model->dogVet->practicename:'' ?>

There is also http://php.net/manual/en/function.is-object.php

Or if you want to do it Yii way try Chtml::value. It’s easy to use and supports default value.

Ok, thank you everyone. will try those recommendations.

QUESTION: Is it OK that I’m using the BELONGS_TO in this fashion?

thank I found solution for my problem :D :D