using relations with CGridView
I'll describe the problom as clearly as I can.
I have activeDataProvider:
$dataProvider=new CActiveDataProvider('Menu', array(
'criteria'=>array(
开发者_运维知识库'with' => array('roles'),
),
));
then I'am using CGridView with checkbox:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'menu-grid',
'selectableRows' => 2,
'dataProvider'=>$dataProvider,
'columns'=>array(
'id',
'title',
array(
'class' => 'SCheckboxColumn',
'header' => 'View',
'name' => 'Roles[Actions][can_view]',
'id' => 'roles_action_can_view',
'value' => '$data->id',
'checkBoxHtmlOptions' =>
array('checked' => $data->roles->can_view),
),
),
));
Then in Menu Model relations:
return array(
'roles' => array(self::HAS_MANY, 'Rolesmenus', 'menu_id'),
);
and in Rolesmenus Model relations:
return array(
'menu' => array(self::BELONGS_TO, 'Menu', 'menu_id'),
);
So, I cant access $data->roles->can_view variable, when I var_dump all $data object I can see these attributes in _attributtes private array but I cant them access through CGridView.
Any ideas??
array('checked' => $data->roles->can_view,),
needs to be array('checked' => '$data->roles->can_view',),
When your relation is a HAS_MANY then calling that relation will return an array of that ActiveRecord. The CGridView won't display an array, so what I have done in the past is write a function in the model that contains the relation to take all the values in the array and create a string from them. For example with your example in the menu model do something like this
public function rolesToString()
{
$roles = $this->roles;
if($roles) {
$string = '';
foreach($roles as $role) {
$string .= $role->can_view . ', ';
}
return substr($string,0,strlen($string)-1); // substr to remove trailing comma
}
return null;
}
then the 'value' attribute of the CGridView for that column should look like this
'value'=>'$data->rolesToString()'
There is some more information about using HAS_MANY, with, and CGridView Here
the best way to clean out the last comma is.. trim(',',string) regards
精彩评论