Get Data From More then one table in CGRIDVIEW or CLISTVIEW in Yii

Often you need to show data from more than one table or from any other table or write custom function in any column of cgridview or clistview. So here I am writing an example how you can achieve this.

Controller function

   public function actionGetmyOfficebrancheslist() {
           /* suppose I have an Office branch So this data provider will have all branches where main branch id will be 1 */

            $dataProvider=new CActiveDataProvider('OfficeBranches',array(
                    'order'=>'last_modified_date DESC',
            )); //office branches is the model object of officebranches table


view officelist.php

In the view file you write cgridview code.

<?php $this->widget('zii.widgets.grid.CGridView', array(
        'id' => 'user-grid',        
                    'class' => 'CButtonColumn',
                     'name'=>'Office Managers',  
                     'type'=>'raw', //for allowing raw html
                     'value'=>'customFunctions::getManagerListFromOfficeBranch($data->officeid)' //here is custom function that will get managers of office branch from office table ($data is used to get any value from current row of branch)
)); ?>


You can create a folder in protected folder with name includes and keep this file in includes folder
Path Exm: /protected/includes/customFunctions.php

Include the file in config/main.php
Exm: require_once realpath(__DIR__ . ‘/../includes/customFunctions.php’);


class customFunctions{

     public static function getManagerListFromOfficeBranch($officeid) {   
        $managerDetails=Office::model()->findAllByAttributes(array('officeid'=> $officeid));  //Office is the model object of Office Table       
        foreach ($managerDetails as $key => $value) {
            $managerList=$managerList.$value->manager->first_name." ".$value->manager->last_name."<br/>";
        echo $managerList;        //all managers echo line by line in the column