0
<?php
//form
class SomeForm extends CFormModel
{
    public $id;
    public $user_id;

    public function search()
    {
        $sql = 'SELECT id, name FROM some_table';
        $sql_count = 'SELECT COUNT(id) FROM some_table';
        return new CSqlDataProvider($sql, array(
            'totalItemCount' => Yii::app()->db->createCommand($sql_count)->queryScalar(),                                    
            'sort' => array(
                'attributes' => array(
                    'id', 'name',
                ),                
            ),
            'pagination' => array(
                'pageSize' => 50,
            ),
        ));
    }

    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'name' => 'NAME',            
        );
    }
}

//grid
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => $model->search(), //$model = new SomeForm()    
    'columns' => array(
        'id',
        'name'
    ),
));
/*
Result:
id | name
---------
1  | John

EXPECTED Result:
ID | NAME
---------
1  | John
*/

如何为查询列设置自定义名称?

4

2 回答 2

1

最简单的方法:

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => $model->search(), //$model = new SomeForm()    
    'columns' => array(
        'id::ID',
        'name::NAME'
    ),
));

其他方式:

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => $model->search(), //$model = new SomeForm()    
    'columns' => array(
        array(
            'header' => 'ID',
            'name' => 'id'
        ),
        array(
            'header' => 'NAME',
            'name' => 'name',
        ),
    ),
));

链接到 api 文档

于 2012-05-23T09:39:15.710 回答
0

如果您不想使用自定义名称;如果你想使用你的模型中声明的标签,那么你可以这样做:

  1. 创建模型的空实例并将其传递给您的视图。因此,视图将使用$data( CSqlDataProvider) 以及空模型。

    $labelModel = new my_model;
    
    $this->widget('zii.widgets.CListView',array(
        'dataProvider'=>$my_model->search(), //returns a CSqlDataProvider
        'itemView'=> '_view',
        'viewData' => array('labelModel' => $labelModel),
    ));
    
  2. 使用空模型 - 连同 getAttributeLabel - 来回显标签。

  3. 用于$data['field_name']回显数据。

链接包含有关如何将附加模型传递给CListViewor的更多信息CGridView

于 2013-05-09T20:50:48.280 回答