Virtual Atttribute

I don’t know why YII has no way to add anything to a model attributes.

if there is a way please tell me. I spend a lot of time trying in vain.

Yes. I know you can add the attribute in the class like this:

class IR extends CActiveRecord


public newAttr = '';

public function afterFind(){

//       give newAttr some value



and latter use it like : ir->newAttr

actually this is usefull, but not in all cases.

eg. I need to send the attributes including the virtual ones via ajax using JSON::encode

so I need to newAttr to be a part of the model’s attributes array. No way I could find to do so.

I used a very dirty way.

I added a new column to the database table whose name is newAttr.

that works for me.

but it’s dirty.

Why don’t you override the [font=“Courier New”][color="#0000FF"]CActiveRecord::getAttributes()[/color][/font] method in your class?

is this possible? :huh:

then how can I add the newAttr to the attributes array?

Something like:

public function getAttributes($names=true) {

    $attributes = parent::getAttributes($names);

    if ($names === true or is_array($names) and array_search('newAttr', $names)) $attributes['newAttr'] = $this->newAttr;

    return $attributes;


I didn’t test it!

very helpful. works! thank you!