Luis Masuelli
Luis Masuelli

Reputation: 12333

Yii - reacting to attribute model assignation

I want to do the following in Yii:

When the attribute `a` in my model class `M` is set, do something.

AND tried using a setter like: setA($value) but it's not called since Yii CActiveRecord first detects if the attribute exists in database (and assigns it) and if it does not exist in database (i.e. it's not a table attribute) then a normal instance variable is looked up. The final fallback is calling a property accesor.

(Edit - I was wrong with resolution order: the lookup seems to be first to an instance variable, then to an attribute, and finally to an accessor - anyway, my problem is still the same since the accesor is resolved if no database field exists with that name)

Here it's shown the internal mechanics of __set (and a bit upper, the __get).

Question: How can I invert the order, at least for a certain attribute? This means: I actually WANT to capture the database field edition with a setter like setA($value), performing the field assignation (i.e. the actual $this->a, however it should be done without falling in a stack overflow error) inside the setA method

Upvotes: 1

Views: 52

Answers (1)

user1233508
user1233508

Reputation:

A reasonable approach would be to override CActiveRecord::setAttribute in your model class to behave the way you need it to:

class M extends CActiveRecord {
  ....
  public function setAttribute($name,$value) {
    if($name === 'a') {
      .. do something
    }

    return parent::setAttribute($name, $value);
  }
  ....
}

Upvotes: 2

Related Questions