Approach to null relationships

Hi,

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']);

    }



What is the best approach to tackle this issue?

Thanks,

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 ?>

@alrazi, Thanks!

Second approach is more convenient.

How about this code for instance?




<?= Html::activeHiddenInput($option->image, 'image_id', ['name' => 'option_data[OptionImages][0][image_id]']) ?>



The same issue on the first parameter, "$option->image".

I managed to solved using your approach in the first reply.

Here’s the code,




public function getImageModel()

    {

    	if (isset($this->image)) {

    		return $this->image;

	    }


	    return new OptionImages();

    }



In views, I replaced "$option->image" with "$option->getImageModel()" and it worked.