Search code examples
phpyiicgridview

Sorting columns with CGridView in Yii based on function call in value


I have these codes in my view file:

    <?php $this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        array(
            'name' => 'Name',
            'type'=>'raw',
            'value' => 'CHtml::link(CHtml::encode($data->profile->first_name." ".$data->profile->last_name),array("match/view","id"=>$data->id))',
        ),
        array(
            'name' => 'Similiarity Score',
            'type'=>'raw',
            'value' => array($this, 'calculateScore'),
        ),
    ),
)); ?>

You will notice that the second column call the function calculateScore($data, $row) in the controller file. Is there anyway I can sort the table based on these scores?


Solution

  • I assume that your result is from a database and you use a CActiveDataProvider or CSqlDataProvider. In this case you will have to move the logic for calculateScore into the DB query somehow. You can add a public property score to your model class and add this to the select property of your CDbCriteria:

    $criteria->select = array('*', '... SQL FOR SCORE CALC HERE ... AS score');
    

    Then you will be able to sort by that score in the sort definition of your CActiveDataProvider:

    'sort' => array(
        'attributes' => array(
            // ...
            'score',