I came across an issue of dealing with hasOne/hasMany relations that does not have corresponding records in DB, as a result, I got errors on views that varies from:
Call to a member function formName() on null
Trying to get property of non-object
Relation Example
public function getImage()
{
return $this->hasOne(OptionImages::className(), ['option_id' => 'option_id']);
}
do a simple if statement to check if the property is not null
if (isset($model->image)) {
// ... access $model->image properties
echo $model->image->filepath; // or whatever
} else {
// no image, display a placeholder
echo 'no image';
}
or you can clean this up a adding a method to your model for instance lets say you trying to get the image filepath from your declared getImage() relationship.
public function getImageFilepath()
{
if (isset($this->image)) {
return $this->image->filepath;
} else {
// this can be an object or default image filepath.
return 'no image';
}
}
// then in your views you don't have to check for null values you can simply call
<?= $model->imageFilepath ?>