Yii Framework Forum: Virtual Atttribute - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Virtual Atttribute the right way Rate Topic: -----

#1 User is offline   Aladdin 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 54
  • Joined: 20-July 11

Posted 16 February 2013 - 06:08 AM

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.
0

#2 User is offline   clapas 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 39
  • Joined: 21-February 11

Posted 16 February 2013 - 06:17 AM

Why don't you override the CActiveRecord::getAttributes() method in your class?
0

#3 User is offline   Aladdin 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 54
  • Joined: 20-July 11

Posted 16 February 2013 - 06:18 AM

View Postclapas, on 16 February 2013 - 06:17 AM, said:

Why don't you override the CActiveRecord::getAttributes() method in your class?

is this possible? :huh:
then how can I add the newAttr to the attributes array?
0

#4 User is offline   clapas 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 39
  • Joined: 21-February 11

Posted 16 February 2013 - 06:31 AM

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!
1

#5 User is offline   Aladdin 

  • Junior Member
  • Pip
  • Yii
  • Group: Members
  • Posts: 54
  • Joined: 20-July 11

Posted 16 February 2013 - 07:17 AM

very helpful. works! thank you!
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users