How to get a simple array of usernames

Hi, in the accessRules() section of a controller, you can set the rules like this:


public function accessRules()

{

	return array(

		array('allow',

			'actions'=>array('view'),

			'users'=>array('user1', 'user2'),

		),

}

So I thought that I could make a function to get a user list to have a nice user access control method without digging into Authentication and Authorization theory (it’s a simple academic project and I don’t have time for that at this moment). I wanted to call the function like this:


public function accessRules()

{

	return array(

		array('allow',

			'actions'=>array('view'),

			'users'=>MyClass::getUserList(1), // $profile_id = 1 is just an example

		),

}

So I made this class (in the "models" folder):


class MyClass

{

	public static function getUserList($profile_id)

	{


		$user = User::model()->findAllByAttributes(array('profile_id'=>$profile_id));

		return $user->getAttributes(array('username'));

	}

}

But it’s not working. The error message is: “Fatal error: Call to a member function getAttributes() on a non-object in /public_html/protected/models/MyClass.php on line xxx”… I don’t know what may be wrong since I’m sure that there are users with the “profile_id” I’m passing.

What am I doing wrong? Would you please suggest how to fix this? or how to do it in a better way? What I want to do is just to get a simple array containing usernames from users having an specific "profile_id", so I can pass that array to the controller accessRules() section.

"User" model has the following fields: id, username, profile_id

Thanks in advance for your help!

The CActiveRecord::findAllBy… methods return an array (of objects or empty), you are treating this array as an object, you’ll need to perform your work on the array elements.

Hope this helps.

Oh I see. Thanks for your answer. However, at this moment I don’t know how to do that. Isn’t there any Yii way to accomplish this task? I mean, without having to do a foreach (or something like that) and manually building the array?

Thank you.




class User extends CActiveRecord

{

    public function getUserList($profile_id)

    {

        $criteria = new CDbCriteria;

        $criteria->select = 'username';

        $criteria->addColumnCondition(array('profile_id'=>$profile_id));

        return $this->getCommandBuilder()->createFindCommand($this->getTableSchema(), $criteria)->queryColumn();

    }

}


public function accessRules()

{

    return array(

        array('allow',

              'actions'=>array('view'),

              'users'=>User::model()->getUserList(1),

        ),

    );

}



Thank you very much Andy for your answer.

However, I just had success using a foreach approach, following the ideas in this topic:

http://www.yiiframework.com/forum/index.php?/topic/21950-array-of-users/

Thank you anyway! I may try your suggestion in the future and I’m sure it will be helpful to other people as well.

Greets.