简体   繁体   中英

Yii - Change column in CGridView for another model's field

In my model (let's say Model A ) I have a field corresponding to the id of another model ( Model B ). In a CGridView composed of Model A items, instead of showing the id of Model B, I want to show another field of that model instance.

Here's how I am showing my CGridView ;

$dataProvider =  new CArrayDataProvider('Model A');
$dataProvider->setData($model_A_Data); // $model_A_data is an array of Model A Objects

$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'data-id',
    'dataProvider'=>$dataProvider, //$objects->search(),
    'columns'=>array(
        array('header'=>'Model A Id', 'name'=>'id'),
        array('header'=>'Name', 'name'=>'name'),
        array('header'=>'Date', 'name'=>'date_created'),
        array('header'=>'Model B Id', 'name'=>'model_b_id'), // *HERE SHOW ANOTHER FIELD OF MODEL B*
    ),  
)); 

How can I change that column in order to show another field of model B clasS?

Thanks

say in Model A i have a relation

array('modelbrelationname','ModelB','id'),

So You can have the value like this

$dataProvider =  new CArrayDataProvider('Model A');
$dataProvider->setData($model_A_Data); // $model_A_data is an array of Model A Objects

$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'data-id',
    'dataProvider'=>$dataProvider, //$objects->search(),
    'columns'=>array(
        array('header'=>'Model A Id', 'name'=>'id'),
        array('header'=>'Name', 'name'=>'name'),
        array('header'=>'Date', 'name'=>'date_created'),
        array('header'=>'Model B Id', 'value'=>'modelbrelationname.id'), // *HERE SHOW ANOTHER FIELD OF MODEL B*
    ),  
)); 

OK, I figured out how to solve this after discovering the $data var in CGridView which holds the corresponding row data.

Simply add this:

array('name'=>'Model B Another Field',
      'value'=> 'ModelB::model()->FindByPk($data->id)->another_field'
),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM