Adiputra Utama
Adiputra Utama

Reputation: 1

Trying to get property of non-object in realtional Yii2

Why my relational 'Trying to get property of non-object' ???

I have model Destination with hasOne() to model AddressDistrict

public function getDestinationAddressDistrict(){
return $this->hasOne(\common\models\AddressDistrict::className(), ['id' => 'DISTRICT']);
}

In model AdressDistrict any field : id, propinsi_id, nama

public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'propinsi_id' => 'Propinsi ID',
            'nama' => 'Nama',
        ];
    }

In controller (actionIndex) I get model Destination :

$modelDestination = new Destination;

and I pass to create then I pass to _form ..

In _form I write $modelDestination->destinationAddressDistrict->id ..and I have that notify.. Any solution ?

Upvotes: 0

Views: 209

Answers (1)

Joe Miller
Joe Miller

Reputation: 3893

Your problem is that you have created a new instance of Destination, so all the fields are empty, so there is no way to get a valid relation based on a value of DISTRICT, as DISTRICT hasn't yet been set.

You have two options. You can either test for the existence of a valid relation, like this;

if ($modelDestination->destinationAddressDistrict){
    //Do something with the `$modelDestination->destinationAddressDistrict->id`
}

or you can assign a default value of DISTRICT so that a valid relation can be generated.

Upvotes: 1

Related Questions