How to use multiple CGridView for different models

Hi…

I dont know How to use multiple CGridView for different models. Please any one suggest me how to do so…

thanks…

Just create 2 different model instances in an action method in a controller, and display 2 CGridView widgets for the corresponding models in the view for the action.

When Gii generates the CRUD codes from a model, the controller doesn’t contain other models in its codes. But don’t think that you have to use just one model in a controller. You can have whatever models you want in a controller.




	public function actionFooBar()

	{

		$model = new Foo('search');

		$model->unsetAttributes();

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

		{

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

		}

		$model2 = new Bar('search');

		$model2->unsetAttributes();

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

		{

			$model2->attributes = $_GET['Bar'];

		}

		$this->render('some_view',array(

			'model' => $model,

			'model2' => $model2,

		));

	}

....

$this->widget('zii.widgets.grid.CGridView', array(

	'id' => 'foo-item-grid',

	'dataProvider' => $model->search(),

	'filter' => $model,

	'columns' => array(

		....

));

$this->widget('zii.widgets.grid.CGridView', array(

	'id' => 'bar-item-grid',

	'dataProvider' => $model2->search(),

	'filter' => $model2,

	'columns' => array(

		....

));



The code is not tested, but something like this would do.

Hi…

Thanks for your response…

I have tried with your code… but i getting the error Undefined variable: model2. i dont know how to rectify it… Plz help me…

thanks

Aruna

Could you post your controller code?

Hi…

I have attached the controller code… I want to display as shown in screenshot instead of project details in second grid ., it must displays the task information when the project link is clicked from the first grid…

Plz help me to solve this…

1788

admin.php

1789

ProjectInfoController.php

1790

project.JPG

thanks…

Aruna

Um, I think you have to try to give us the minimal lines of code that can be relevant to the issue. And preferably with the code snippet markup, not with the file attachments …

Anyway, here’s the lines that can be relevant:

So, let’ see …

Hi…

Sorry for attaching the file like that… Can you plz tell me wat mistake i have done…

thanks…

admin view (admin.php) is trying to render 2 grids: one with a model named $model, and another with a model named $model2.

But when you try to render admin view from admin action of the controller, you are passing just one model named model.

If you want the 2nd grid (task-info-grid) to be rendered in the admin view properly, you have to pass the 2nd model to the view from the controller.

Also you have to think about the initial call of the admin action, where there’s no project selected by the user yet. You may hide the 2nd grid, or select some default project to render the task info.

How about this … I hope it will do something close to your needs.




// admin.php

......

if ( $model2 !== null ) // only when $model2 is set

{

	$this->widget('zii.widgets.grid.CGridView', array(

		'id'=>'task-info-grid',

		'dataProvider'=>$model2->search(),

		'filter'=>$model2,

		'columns'=>array(

			'task_id',

			'task_name',

		),

	));

}

......


// ProjectInfoController.php

......

	public function actionAdmin($id = null)  // $id defaults to null for the initial call

	{

		$model=new ProjectInfo('search');

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

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

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

			

		$model2 = null;      // $model2 defaults to null

		if ( $id !== null )  // but when called from the admin view with id specified

		{

			$model2 = new TaskInfo('search');

			$model2->unsetAttributes();

-			$model2->id = $id;   // filters for the project with the id

+			$model2->something = $id;   // filters for the project with the id

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

			{

				$model2->attributes = $_GET['TaskInfo'];

			}

		}

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

			'model'=>$model,

			'model2'=>$model2,

		));

	}

......



[EDIT]




-			$model2->id = $id;   // filters for the project with the id



The line above was misleading.

Hi…

Im trying … with the code … it is not showing any error… but it displays the same as in screenshot view no change …

Much thanks… for spending time to help me…

Are you referring to the "admin" page or "manage" page?

Well, your screenshot should be that of the “manage” page (actionProjectInfoTaskInfo and manage.php), wasn’t it? But I thought that we are discussing about the “admin” page (actionAdmin and admin.php), because your error was caused by the mismatch of the passed variables from the actionAdmin method to the view.

If your “admin” page doesn’t change the 2nd grid when you hit the link of the project name in the first grid, um, I have no idea right now.

Hello All…

Can any one help me to solve this Plz…

thanks…

Could you post your current codes for the controller and the view?

Hi…

I have posted the controller and view file

Controller.php


<?php

class ProjectInfoController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';


	

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

		);

	}

	

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('admin'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	

	public function actionView($id)

	{

		$this->render('view',array(

			'model'=>$this->loadModel($id),

		));

		

	}


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new ProjectInfo;

		

		

		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['ProjectInfo']))

		{

			$model->attributes=$_POST['ProjectInfo'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->project_id));

		}

		

		$this->render('create',array(

			'model'=>$model,

					));

	}


	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 */

	public function actionUpdate($id)

	{

		$model=$this->loadModel($id);


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['ProjectInfo']))

		{

			$model->attributes=$_POST['ProjectInfo'];

			if($model->save())

				$this->redirect(array('view','id'=>$model->project_id));

		}


		$this->render('update',array(

			'model'=>$model,

		));

	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'admin' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

			$this->loadModel($id)->delete();


			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

			if(!isset($_GET['ajax']))

				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}





/*public function actionProjectInfoTaskInfo()

        {

                $model = new ProjectInfo('search');

                $model->unsetAttributes();

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

                {

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

                }

                $model2 = new TaskInfo('search');

                $model2->unsetAttributes();

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

                {

                        $model2->attributes = $_GET['TaskInfo'];

                }

                $this->render('manage',array(

                        'model' => $model,

                        'model2' => $model2,

                ));

        }*/


	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('ProjectInfo');

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}


	/**

	 * Manages all models.

	 */

	 public function actionAdmin($id = null)  

        {

                $model=new ProjectInfo('search');

                $model->unsetAttributes();  

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

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

                        

                $model2 = null;      

                if ( $id !== null )  

                {

                        $model2 = new TaskInfo('search');

                        $model2->unsetAttributes();

                        $model2->id = $id;   

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

                        {

                                $model2->attributes = $_GET['TaskInfo'];

                        }

                }

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

                        'model'=>$model,

                        'model2'=>$model2,

                ));

        }

/*	public function actionAdmin()

	{

		$model=new ProjectInfo('search');

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

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

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


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

			'model'=>$model,

		));

	}*/


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer the ID of the model to be loaded

	 */

	public function loadModel($id)

	{

		$model=ProjectInfo::model()->findByPk((int)$id);

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

		

	}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='project-info-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

}

view.php


<?php

$this->breadcrumbs=array(

	'Project Infos'=>array('index'),

	$model->project_id,

);


$this->menu=array(

	array('label'=>'List ProjectInfo', 'url'=>array('index')),

	array('label'=>'Create ProjectInfo', 'url'=>array('create')),

	array('label'=>'Update ProjectInfo', 'url'=>array('update', 'id'=>$model->project_id)),

	array('label'=>'Delete ProjectInfo', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->project_id),'confirm'=>'Are you sure you want to delete this item?')),

	array('label'=>'Manage ProjectInfo', 'url'=>array('admin')),

);

?>


<h1>View ProjectInfo #<?php echo $model->project_id; ?></h1>


<?php $this->widget('zii.widgets.CDetailView', array(

	'data'=>$model,

	'attributes'=>array(

		'project_id',

		'project_name',

		

		/*array(

'name'=>'project_type_id',

'value'=>CHtml::encode($model->getTypeText())

),*/


/*array(

'name'=>'project_status_id',

'value'=>CHtml::encode($model->getStatusText())

),*/


array(

'name'=>'project_type_id',

'value'=>CHtml::encode($model->projectType->project_type)

),


array(

'name'=>'project_status_id',

'value'=>CHtml::encode($model->projectStatus->project_status_name)

),

		array(

'name'=>'client_id',

'value'=>CHtml::encode($model->client->client_name)

),

		'client_comment',

		array(

'name'=>'team_id',

'value'=>CHtml::encode($model->team->team_name)

),

		'project_des',

		'project_start_date',

		'project_end_date',

		'total_dur',

		'point_id',

		'upload',

		'project_created_on',

	),

)); ?>



Might be …




// view: admin.php

......

$this->widget('zii.widgets.grid.CGridView', array(

	'id'=>'project-info-grid',

	'dataProvider'=>$model->search(),

	'filter'=>$model,

	'columns'=>array(

		'project_id',

		 array(

			'name' => 'project_id',

			'type' => 'raw',

			'value' => 'CHtml::link(CHtml::encode($data->project_name),array("projectInfo/admin","id"=>$data->project_id))',

		),

		array(          

			'name'=>'project_type_id',

			'value'=>'$data->projectType->project_type',

		),

		array(          

			'name'=>'project_status_id',

			'value'=>'$data->projectStatus->project_status_name',

		),

		'client_comment',

		array(

			'name'=>'client_id',

			'value'=>'$data->client->client_name',

		),

		array(

			'class'=>'CButtonColumn',

		),

	),

));

if ( $model2 !== null ) // only when $model2 is set

{

	$this->widget('zii.widgets.grid.CGridView', array(

		'id'=>'task-info-grid',

		'dataProvider'=>$model2->search(),

		'filter'=>$model2,

		'columns'=>array(

			'task_id',

			'task_name',

		),

	));

}

......


// controller: ProjectInfoController.php

......

	public function actionAdmin($id = null)  // $id defaults to null for the initial call

	{

		$model=new ProjectInfo('search');

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

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

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

			

		$model2 = null;      // $model2 defaults to null

		if ( $id !== null )  // but when called from the admin view with id specified

		{

			$model2 = new TaskInfo('search');

			$model2->unsetAttributes();

			$model2->xxxx = $id;   // You should know what it should be ...

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

			{

				$model2->attributes = $_GET['TaskInfo'];

			}

		}

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

			'model'=>$model,

			'model2'=>$model2,

		));

	}

......






			$model2->xxxx = $id;   // You should know what it should be ...



This will cause an error.

You have to give a proper attribute of the TaskInfo … probably "project_id", I guess.

Thank you soo much… softark, It Worked…

I’m glad, too.

Sorry for your confusion regarding the "id" in my code. It was misleading.

Hi…

I was getting Error 500:…in search, suggest me plz how to clear this error…


Error 500: <h1>PHP Error [2]</h1>

<p>htmlspecialchars() expects parameter 1 to be string, array given (C:\yii-1.1.8.r3324\framework\web\helpers\CHtml.php:66)</p>

<pre>#0 unknown(0): CWebApplication->handleError()

#1 C:\yii-1.1.8.r3324\framework\web\helpers\CHtml.php(66): htmlspecialchars()

#2 C:\yii-1.1.8.r3324\framework\web\helpers\CHtml.php(2137): encode()

#3 C:\yii-1.1.8.r3324\framework\web\helpers\CHtml.php(122): renderAttributes()

#4 C:\yii-1.1.8.r3324\framework\web\helpers\CHtml.php(1794): tag()

#5 C:\yii-1.1.8.r3324\framework\web\helpers\CHtml.php(1199): activeInputField()

#6 C:\yii-1.1.8.r3324\framework\zii\widgets\grid\CDataColumn.php(99): activeTextField()

#7 C:\yii-1.1.8.r3324\framework\zii\widgets\grid\CGridColumn.php(103): CDataColumn->renderFilterCellContent()

#8 C:\yii-1.1.8.r3324\framework\zii\widgets\grid\CGridView.php(445): CDataColumn->renderFilterCell()

#9 C:\yii-1.1.8.r3324\framework\zii\widgets\grid\CGridView.php(423): CGridView->renderFilter()

#10 C:\yii-1.1.8.r3324\framework\zii\widgets\grid\CGridView.php(393): CGridView->renderTableHeader()

#11 C:\yii-1.1.8.r3324\framework\zii\widgets\CBaseListView.php(158): CGridView->renderItems()

#12 unknown(0): CGridView->renderSection()

#13 C:\yii-1.1.8.r3324\framework\zii\widgets\CBaseListView.php(141): preg_replace_callback()

#14 C:\yii-1.1.8.r3324\framework\zii\widgets\CBaseListView.php(126): CGridView->renderContent()

#15 C:\yii-1.1.8.r3324\framework\web\CBaseController.php(166): CGridView->run()

#16 C:\wamp\www\pms\protected\views\projectInfo\view.php(107): ProjectInfoController->widget()

#17 C:\yii-1.1.8.r3324\framework\web\CBaseController.php(119): require()

#18 C:\yii-1.1.8.r3324\framework\web\CBaseController.php(88): ProjectInfoController->renderInternal()

#19 C:\yii-1.1.8.r3324\framework\web\CController.php(866): ProjectInfoController->renderFile()

#20 C:\yii-1.1.8.r3324\framework\web\CController.php(779): ProjectInfoController->renderPartial()

#21 C:\wamp\www\pms\protected\controllers\ProjectInfoController.php(68): ProjectInfoController->render()

#22 unknown(0): ProjectInfoController->actionView()

#23 C:\yii-1.1.8.r3324\framework\web\actions\CAction.php(104): ReflectionMethod->invokeArgs()

#24 C:\yii-1.1.8.r3324\framework\web\actions\CInlineAction.php(48): CInlineAction->runWithParamsInternal()

#25 C:\yii-1.1.8.r3324\framework\web\CController.php(300): CInlineAction->runWithParams()

#26 C:\yii-1.1.8.r3324\framework\web\filters\CFilterChain.php(134): ProjectInfoController->runAction()

#27 C:\yii-1.1.8.r3324\framework\web\filters\CFilter.php(41): CFilterChain->run()

#28 C:\yii-1.1.8.r3324\framework\web\CController.php(1144): CAccessControlFilter->filter()

#29 C:\yii-1.1.8.r3324\framework\web\filters\CInlineFilter.php(59): ProjectInfoController->filterAccessControl()

#30 C:\yii-1.1.8.r3324\framework\web\filters\CFilterChain.php(131): CInlineFilter->filter()

#31 C:\yii-1.1.8.r3324\framework\web\CController.php(283): CFilterChain->run()

#32 C:\yii-1.1.8.r3324\framework\web\CController.php(257): ProjectInfoController->runActionWithFilters()

#33 C:\yii-1.1.8.r3324\framework\web\CWebApplication.php(277): ProjectInfoController->run()

#34 C:\yii-1.1.8.r3324\framework\web\CWebApplication.php(136): CWebApplication->runController()

#35 C:\yii-1.1.8.r3324\framework\base\CApplication.php(158): CWebApplication->processRequest()

#36 C:\wamp\www\pms\index.php(13): CWebApplication->run()

</pre>

thanks…

The error message seems to indicate that one of the columns in a CGridView failed to display the text field of the filter cell.

So, do you have any idea which column is causing the error?

Hi…

I cannot able to find which column is causing the error… I have attached the code below… I think… the line which is underlined in the code causing error… Is that right… and now i have changed it to display in view and not admin… help me how to solve this plz…


<?php

class ProjectInfoController extends Controller

{

	public $layout='//layouts/column2';


	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

		);

	}

	 

	 public function actionView($id=null)

	 {

	            if($id!== null)  

                {

                                                

                        $model2 = new TaskInfo('search');

                        _________________________________


          		$model2->unsetAttributes();

                        $model2->task_id = $id;   

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

                        {

                                $model2->task_id = $_GET['TaskInfo'];

						}		

               	}

                        

                $this->render('view',array(

                        'model'=>$this->loadModel($id),

                        'model2'=>$model2,

                ));

				}

	

	public function loadModel($id)

	{

		$model=ProjectInfo::model()->findByPk((int)$id);

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}

	

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='project-info-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}

	

}



TaskInfo.php


/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;

		if(isset($_GET['id'])){

			$id=$_GET['id'];

			$criteria->condition="project_id=$id";

			}

		$criteria->compare('task_id',$this->task_id);

		$criteria->compare('task_name',$this->task_name,true);

		$criteria->compare('project_id',$this->project_id);

		$criteria->compare('task_type_id',$this->task_type_id);

		$criteria->compare('task_des',$this->task_des,true);

		$criteria->compare('task_end_date',$this->task_end_date,true);

		$criteria->compare('totaltime',$this->totaltime,true);

		$criteria->compare('emp_id',$this->emp_id);

		$criteria->compare('task_create_at',$this->task_create_at,true);

		$criteria->compare('uploads',$this->uploads,true);

		return new CActiveDataProvider(get_class($this), array(

			'criteria'=>$criteria,

		));

	}

}