AntiGMO
AntiGMO

Reputation: 1587

Yii CGridView can't show custom SQL attribute

In the Type model's search() function, I want to display three attributes in CGridview:

type.name, type.description and count(dataset_type.dataset_id)

public function search()
{
    // Warning: Please modify the following code to remove attributes that
    // should not be searched.

    $criteria=new CDbCriteria;
            $criteria->alias='t';
            $criteria->select='t.name, t.description, count(dataset_type.dataset_id) as number';
            $criteria->join='LEFT JOIN dataset_type ON dataset_type.type_id=t.id';
            $criteria->group='t.id';


    return new CActiveDataProvider($this, array(
        'criteria'=>$criteria,
    ));
}

This is the view:

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id' => 'type-grid',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'itemsCssClass' => 'table table-bordered',
    'columns' => array(
        'name',
        'description',
        'number',
        array(
            'class'=>'CButtonColumn',
        ),
    ),
)); ?>

but in this way the columns in CGridView can only display model attributes, it shows type.number can't find in model Type, how can I display the count()?

Upvotes: 1

Views: 138

Answers (1)

Samuel Liew
Samuel Liew

Reputation: 79063

You will also have to add the attribute to your model to be able to use it as a column in your CGridView:

class Type extends CActiveRecord {

    public $number;

Upvotes: 1

Related Questions