Search in the BELONGS_TO model column with CGridView, Yii

I have a CGridView widget for a Lesson model

$this->widget('zii.widgets.grid.CGridView', array( 'id'=>'lesson-grid', 'dataProvider'=>$model->search(), 'filter'=>$model, 

... and Lesson is related to the User model:

 'user' => array(self::BELONGS_TO, 'User', 'user_id'), 

... and CGridView has a column with the username from the BELONGS_TO model described above

 'columns'=>array( ... array( 'name' => 'user', 'header'=>'Teacher', 'value' => '$data->user->lastname', ), 

Thus, I cannot perform a search in the CGridView in this column, but I need it.

How to search in '$ data-> user-> secondname' using CGridView?

I think I should extend the search method in the Lesson model, but how?

Now it looks like this:

 public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id); $criteria->compare('student',$this->student,true); $criteria->compare('comment',$this->comment,true); return new CActiveDataProvider(get_class($this), array( 'criteria'=>$criteria, )); } 
+4
source share
1 answer

This should work, add it to the search criteria in the search () method:

 $criteria->with[]='user'; $criteria->addSearchCondition("user.secondname",$this->user_id); 

This is what I do:

 if(!intval($this->user_id) && is_string($this->user_id) && strlen($this->user_id) > 0) { $criteria->with[]='user'; $criteria->addSearchCondition("user.secondname",$this->user_id); } else $criteria->compare('t.user_id',$this->user_id); 

And here is the definition of CGridView:

 'columns'=>array( ... array( 'name' => 'user_id', 'header'=>'User', 'sortable'=>false, // since it would still be sorting based on ID // 'value' => '$data->user->lastname', // basic version 'value'=>'CHtml::link((isset($data->user))?$data->user->username:$data->user_id,array("user/view","id"=>$data->user_id))', // link version ), 

This is a funny little trick: if the search term is a string and is NOT intval (), it searches for the user by his name, through the user relationship. But if you enter user_id, it will find the user by their user_id - the default search function ().

NOTE. This will allow filtering, but will still be sorted based on identifier. You will need to implement something extra to make the sorting work.

Of course, there are other ways to do this, but I do. I suspect there is a โ€œrightโ€ to do this using an attitude, but my technique works solidly.

+8
source

Source: https://habr.com/ru/post/1337840/


All Articles