Search code examples
phpexceptionyii2relationnotice

Yii2 function based on relation gives error on create


I have this in my model called B:

public function getA() {
    return $this->hasOne(\app\models\A::className(), ['id' => 'A_Id']);
}

public function getDispName() {
    return $this->a->attr . ' ' . $this->attr . ' ' . $this->attr2;
}

works everything fine, until I go to Create. Then I get the following "error":

PHP Notice – yii\base\ErrorException Trying to get property of non-object

As a workaround I have done this:

public function getDispName() {
    if (is_object($this->a)) {
        return $this->a->attr . ' ' . $this->attr . ' ' . $this->attr2;
    }
}

I'm not sure if this is a good solution, or why do I get this "notice" only at create, but I would like to understand and do it correctly. I don't want this to cause problems somewhere else. Maybe I miss something other basic and important knowledge. If you have any ideas, I would be grateful to hear it. Thanks.


Solution

  • You are probably trying to use a B model that does not have a A model attached. If that is the case of course your function would fail. Are you sure for every B you have an A? Probably you are inserting a B and not inserting an A and trying to show info on it.

    Your options are:
    1) do exactly like you did, maybe change it to

    public function getDispName() {
        $display = '';
        if (is_object($this->a)) {
            $display = $this->a->attr;
        }
        return $display . ' ' . $this->attr . ' ' . $this->attr2;
    }
    

    2) fix your code to always make sure you insert an A when you insert a B. It can be an empty record but it has to be a record.