Tasks Widget

I needed to display a list of authorized tasks according to who’s logged in. The following class helped:




class TaskWidget extends CWidget

{

  protected $tasks = array();


  public function init()

  {

    $this->id = 'tasks';

    $this->header = 'Tasks';


    $user = user()->isGuest ? am()->getAuthItem('guest') : user();

    $type = AuthItemType::model()->findByAttributes(array('name' => 'Task'));


    $params = array(); // Put any context parameters in here for the bizRules, such as the SiteID, etc


    foreach($type->auth_items as $task) {

      $task->data = unserialize($task->data);

      $user->checkAccess($task->name, $params) and $this->tasks[] = $task;

    }

  }


  protected function getContent()

  {

    return $this->render('widget', array('tasks' => $this->tasks), true);

  }

}



Note that I use the data model to find the tasks, rather than AuthManager, because I have enhanced the AuthItem table schema to include other fields which store item-related information (such as title, URI, etc). You can use the Yii::app()->authManager->getAuthItem() as well. Since I’m using the model, the ‘data’ field must be deserialized before use.

Also notice that the distinction between guest and authenticated user is invisible, because both AuthItem and CWebUser have a checkAccess method. To define auth_items for your guest, simply assign tasks to the guest role.

This can be used as a task-oriented navigation element, replacing the main menu if you wish… :)