Search code examples
phpyiicgridview

Yii - CGridView


I am writting my first application with Yii (v1.1.12), and the learning curve is a bit steep for me, so I need some help.

Imagine the following tables (with their relations):

  • detail (n:1) document
  • document (n:1) user
  • user (n:1) department
  • document (n:1) category

user is the table that holds the information about the users that can login and use the application.

I have managed to put together (using Gii and hacking about) a view that lists all the documents, and have also managed to display the category name instead of the category ID in the grid.

One of the features I want to implement is allow the user switch the view so (a) only the documents relating to the logged in user are listed, or (b) only the documents relating to his/her department.

I looked around a bit with no luck. Can anyone help?

Cheers, George

UPDATE: Currenlty I display the list of documents using zii.widgets.grid.CGridView.

UPDATE 2: Following Omar's reference to CDbCriteria I found this URL with a bit more detail on the subject.

I came up with the following model code, that works fine:

public function searchByUser($user_id)
{
   $criteria=new CDbCriteria;
   $criteria->condition = " user_id = ".$user_id;
   return new CActiveDataProvider($this, array(
          'criteria'=>$criteria,
   ));
}
public function searchByDepartment($user_id)
{
   $criteria=new CDbCriteria;
   $criteria->alias="p";
   $criteria->join = "JOIN (SELECT u.id 
                              FROM user u 
                             INNER JOIN user uu 
                                ON u.department_id = uu.department_id 
                             WHERE uu.id = ".$user_id.") uu 
                                ON p.user_id = uu.id";                  
    return new CActiveDataProvider($this, array('criteria'=>$criteria,));
}

While the above works as expected, I was hoping for a solution that would not require me to write chopped SQL code at all. Not due to lazyness, but just to leverage more of the functionality of the framework.

I just have the feeling that this approach doesn't follow best practices (?).


Solution

  • Try to create your own CDBCriteria and define whatever conditions inside it and pass it as data provider to your grid view.

    If you allowed the search inside the grid view, pass the criteria to the search function, and inside it, merge the passed criteria with criteria inside the search.