List All Articles Written By User

Hi,

I have small application, where users input some data. All users can list all saved reports.

Is it possible to restrict access that only each user can list their own reports.

Where can I do it?

Does CListView class have an option to enable to show only owners arcticles?

My view.php looks like this:


<?php

$this->breadcrumbs=array(

	'Raports',

);


if(Yii::app()->user->role == "coord")

{

	$this->menu=array(

//	array('label'=>'Create Raport', 'url'=>array('create')),

//	array('label'=>'Manage Raports', 'url'=>array('admin')),

	);

}

else {

	$this->menu=array(

	array('label'=>'Create Raport', 'url'=>array('create')),

//	array('label'=>'Manage Raports', 'url'=>array('admin')),

	);

}

?>


<h1>Raports</h1>


<?php $this->widget('zii.widgets.CListView', array(

	'dataProvider'=>$dataProvider,

	'itemView'=>'_view',

)); ?>

In your $dataProvider add a condition where it only allows current user… i.e. if you are using the default gii created it should be your $model->search()

maybe something like this

in your controller




$user_id = your_user_id;

$dataProvider =>$model->search($user_id);



in your model




public function search($user_id)

{

$criteria=new CDbCriteria;

//used for lazy load...this would be your relation to reports 

//$criteria->with = array('user');

//$criteria->together = true;

//user_id would be the relating column to your user table to show ownership of the report

$criteria->addCondition('user_id ='.$user_id);

return new CActiveDataProvider($this, array(

'criteria'=>$criteria,

));

}

This will return only items for the current user. If you use this else where it won’t work without declaring a $user_id in the function ie. search($user_id). You could create two different search functions maybe a user_search($user_id) and search()

I wouldnt do it that way.

Just add to your search method this:




$criteria->condition = 'user_id = :user';

$criteria->params = array(':user'=>Yii::app()->user->id);



And you grid will be filtered by the current user ID.

AlexInt is right. I misread your post…I though you wanted it optional, not all the time.


$criteria->condition = 'user_id = :user';

$criteria->params = array(':user'=>Yii::app()->user->id);

would be the best way to do this.

Ok, I’ve done this using named scopes.

In model:




public function scopes()

    {

        return array(

            'findUsersRaports'=>array(

                'condition'=>"UserName='".Yii::app()->user->name."'",

				'order'=>'Id DESC',

				),   

        );

    }



And in my controller




public function actionIndex() {

     if(Yii::app()->user->role == "myRole") {

     $dataProvider=new CActiveDataProvider(Raport::model()->findUsersRaports());

     $this->render('index',array(

	'dataProvider'=>$dataProvider,

	));

     }

///rest of the code