In my module I run the following code in order to collect the user ids.
The problem is that the attached behavior’s method getId() cannot be run on the user models.
I get the following error:
Property "User.getId" is not defined.
Here is my code:
......
// Attach my behavior to the user model class
CActiveRecord::model($userClass)->attachBehavior('myBehavior', new MyUserBehavior);
// Fetch all the users
$users = CActiveRecord::model($userClass)->findAll($criteria);
// Collect the ids
$userIdList = array();
foreach( $users as $u )
{
$u->enableBehavior('myBehavior'); // This doesn't change anything.
$userIdList[] = $u->getId();
}
......
If I look into one of the user objects I can see the behavior attached but still it’s methods cannot be called.
I’m out of ideas, any help would be appreciated.
Thanks in advance.
Solution:
You have to attach the behavior to each instance separately for everything to work properly. Thanks for all the answers!
CActiveRecord::model($userClass)->attachbehavior('mybehavior', new MyUserbehavior);
you are creating a new model instance for class $userName, and then attach a behavior to it, and then … then nothing ! I mean, the instance you have created does have a ‘mybehavior’ behavior, but you are not using this instance anymore.
Then on the second line …
// Fetch all the users
$users = CActiveRecord::model($userClass)->findAll($criteria);
… you’re creating a new instance for class $userClass and this time you use it to fetch rows … but you have not attached any behavior to this instance.
So the solution would be to write something like :
$m=CActiveRecord::model($userClass);
$m->attachbehavior('mybehavior', new MyUserbehavior);
$users = $m->findAll($criteria);
// Collect the ids
$userIdList = array();
foreach( $users as $u )
{
$userIdList[] = $u->getId();
}
Maybe I’m missing something but I think this should work.
Of course another solution would be to declare behaviors inside the model class definition (like described here) but as you are dynamically creating Models, I guess this doesn’t fit your needs.
I know it works if I attach the behavior separately to each instance of the model. However, I was hoping that it would be possible to avoid calling attachBehavior multiple times. Unfortunately it doesn’t seem possible.
Unfortunately the user class isn’t a part of the module. This is why I cannot use the user model’s behavior-method in this case.
Sure it’s possible but it would require developers using my module to manually add my user behavior to their user model which I don’t want because it’s prone to error.