Use Search Method And Add User_Id

Hi,

For the index or admin action I use the standard gii generated search() method. But I also want to show only the items from the user only. So I use:




	// Admin.

	public function actionAdmin()

	{

		$model=new Item('search');

		$model->unsetAttributes();  // clear any default values

		$model->user_id = Yii::app()->user->id; // <- added this line.

		

		if(isset($_GET['Item']))

			$model->attributes=$_GET['Item'];


		$this->render('item/admin',array(

			'model'=>$model,

		));

	}



But then I want to show a message if there are no items so I tried:


<?php if(count($model) ==0): ?>

But this counts all items, no matter the user_id. The gridview works fine, only showing the user items, because it use as a dataProvider $model->search().

So then I tried using this:


<?php if(count($model->search()->getData()) ==0): ?>

And this works. But now I started to wonder, Am I doing it correct?

So I changed the action in:




	// Admin.

	public function actionAdmin()

	{


		$criteria = new CDbCriteria();

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

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

		$model = Item::model()->findAll($criteria);

	

		if(isset($_GET['Item']))

			$model->attributes=$_GET['Item'];


		$this->render('item/admin',array(

			'model'=>$model,

		));

	}



But then my GridView won’t work anymore, which seems logic since a FindAll returns a ActiveRecord object and not a list of objects like the aActiveDataProvider would (correct me if i’m wrong).

So, am I’m doing it right or is there a better wat to do this?

Hi Bjorn,

The easiest way is to use emptyText property of CGridView. It should work fine with your first code snippet. :)

$model in the controller method is an model instance to hold the search parameters. It is not the search result itself. We use it to receive the user inputs by “$model->attributes = $_GET[‘Item’];”. That’s why you can filter the search result by setting $model->user_id.

The search result is returned by a CActiveDataProvider that is created by $model->search().

Please take a look at this wiki. It will clarify what I’m trying to say.

http://www.yiiframework.com/wiki/381/cgridview-clistview-and-cactivedataprovider

Awesome, thanks a lot for pointing out the emptyText property!

Also thanks a lot for pointing me to this wiki. I believed that I almost got it, but wanted to be sure. So gonne read through this wiki right now to clear things up.

Thanks again! :D