CGridView do not show model attributeLabels

Why CGridView doesn’t show attributeLabels but attribute names instead?

What is the best way to fix this?

Create a new webapp with Yii… create a model and crud with Gii… .and you will see that in fact CGridView displays attributeLabels…

So it should be something in your code…

To get better help from forum users… please read the Guidelines for posting in the forum - http://www.yiiframework.com/forum/index.php?/topic/19451-guidelines-for-posting-this-forum/page__view__findpost__p__95363

According to the source codes in "yii/framework/zii/widgets/grid/CDataColumn.php"




protected function renderHeaderCellContent()

{

    if($this->grid->enableSorting && $this->sortable && $this->name!==null)

        echo $this->grid->dataProvider->getSort()->link($this->name,$this->header);

    else if($this->name!==null && $this->header===null)

    {

        if($this->grid->dataProvider instanceof CActiveDataProvider)

            echo CHtml::encode($this->grid->dataProvider->model->getAttributeLabel($this->name));

        else

            echo CHtml::encode($this->name);

    }

    else

        parent::renderHeaderCellContent();

}



If sorting for that particular column is not disabled (column sorting is enabled by default), the label will be automatically resolved if your model derives from CActiveRecord (for more info, refer to "yii/framework/web/CSort.php")

If sorting for that particular column is disabled, the label will be automatically resolved (getAttributeLabel) if your data provider is an instance of CActiveDataProvider.

If your model doesn’t derive from CActiveRecord AND/OR your data provider is not an instance of CActiveDataProvider, you will have to explicitly resolve the labels.

In order to resolve them explicitly, first add the function attributeLabels() in your model (if you’re using gii to generate your codes, chances are the function is already added for you)




class Product extends CModel {

    public function attributeLabels() {

        return array(

            'title'=>'Product Title',

            'description'=>'Product Description',

        );

    }

}



And then in your view,




<?php

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

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

    'filter' => $model,

    'columns' => array(

        array(

            'name'=>'title',

            'header'=>$model->getAttributeLabel('title'),

        ),

        array(

            'name'=>'description',

            'header'=>$model->getAttributeLabel('description'),

        ),

    ),

    'selectableRows' => 0,

    'htmlOptions' => array('style' => 'width:700px'),

));

?>