bcmcfc
bcmcfc

Reputation: 26765

Setting an array of related models in Yii from form input

In Yii, the following doesn't work (the relation array remains empty) and doesn't return an error:

foreach ($data as $k => $relatedModelData){
    //construct the related model from the data passed in
    ...
    $model->arrayOfRelatedModels[] = $relatedModel;
}

Instead, I have to do this:

foreach ($data as $k => $relatedModelData){
    //construct the related model from the data passed in
    ...
    $tempArray[] = $relatedModel;
}

$model->arrayOfRelatedModels = $tempArray;

I am wondering why this is the case, or whether I have got something slightly wrong in the first example?

Upvotes: 3

Views: 188

Answers (1)

Paystey
Paystey

Reputation: 3242

@o_nix is right, you should be getting the:

Indirect modification of overloaded property error. It's something i've come across a lot recently.

It means that Yii is returning you a magic attribute via the __get function, the object doesn't really exist on the class, and when you set this object it goes through the magic __set function. This means if you try and change something inside the object itself (inner array values for example) it has no idea what to do with them and so it throws up that notice and leaves it alone.

To get round this you did the right thing, modify a new local variable and set the whole object to this once you're done.

P.S
You might have your PHP configuration set to hide notices, which is why it's silent.

Hope that clears it up

Upvotes: 1

Related Questions