Search On A Custom Field

Hi.

I’ve got three views called users, tasks and userTasks. In userTasks admin/manage view it shows user_id and tasks_id by default but I’ve added a new field called userName. It shows all the usernames but the search doesn’t work.

I’ve added this field into the search functions in the model but nothing happens.

Any ideas?

Show us more details, how you define your views and how you build criteria for searching. You probably need to enable eager loading instead of lazy loading.

Yes, you need to provide more detail.

My best guess is that you did not add your new field to the rules as a ‘safe’ field (at least for the search scenario).

Hi, please see exmaple…

1) model.php




	public function relations() {

    	return array(

        	'users' => array(self::BELONGS_TO, 'users', 'user_id'),

   			);

	}

  

2) admin.php




    	array(

        	'name'=>'user_id',

        	'value'=>'$data->users',

        	or

        	'value'=>'Users::Model()->FindByPk($data->user_id)->username',

    	),

  

3) Then after filer search code

=>put your code in serch function




	if(isset($this->user_id) && !empty($this->user_id)){

        	$criteria = new CDbCriteria;

        	$criteria->select = 't.*, tu.* ';

        	$criteria->join = ' LEFT JOIN `users` AS `tu` ON t.user_id = tu.id';

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

    	} 	

  

I hope it’s some help.

You do not show how you defined the new field;

You do not show if the new field is in the rules.

I think you are doing overly complex to show the value in the grid.

Have a look at (the demo of) RelatedSearchBehavior; it will give some idea about the use of CGridView and fields in relations.

In my admin.php I added this to see the username instead of the id.




array(

			'name'=>'user_name',

			'value'=>'$data->user->name'),




In my model I added the new field into the rules function as safe on search. I’ve added it into the attributeLabels() function.

Now I have to add something into the search() function but I don’t really know what to add and how to add it. I tried the code that Maggie Q(Ankit Modi) shared but isn’t working.

EDIT: nevermind, it’s working now with these three lines:




$criteria->together  =  true;

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

        $criteria->compare('user.name',$this->user_name,true);