Yii gridview use outside variable in value

Ross Mike picture Ross Mike · Jul 21, 2012 · Viewed 20k times · Source

I have a function in my Teacher model which returns categories array.

getCaterogies() {
   return array('1' => 'short tempered', '2' => 'funny', '3' => 'visionary', ...);
}

I am storing indexes in database and displaying values everywhere using the value of the array corresponding to that..

$categories = $teacher->categories;
$category = $categories[$teacher->category];

I am doing this because once somebody suggested to me not to store strings in a database which are statuses, instead store integer values, and either store the conversion in the database or define it in ht model. The problem with strings is that they are more prone to human errors in comparisons. Maybe because of case sensitiveness.

Now the problem I am facing is that while displaying values in gridview, I need to write the 2 lines in a value field, but it is an expression, and outside variables also it doesn't take.

How can I get this working for gridview?

Answer

Rajat Singhal picture Rajat Singhal · Jul 21, 2012

You can use anonymous function as value which can take $row, $data params where $row holds the row number (zero-based) and $data contains the data model for the row.

That way you can have it defined inside only.

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        array(
            'name'=>'..',
            'value'=>function($data,$row){
                $categories = $teacher->categories;
                return $categories[$data->category];
            },
        ),
    ),
));

And if you want to use it from outside, you can rely on PHP's use:

$categories = $teacher->categories;
$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider'=>$dataProvider,
    'columns'=>array(
        array(
            'name'=>'..',
            'value'=>function($data,$row) use ($categories){
                return $categories[$data->category];
            },
        ),
    ),
));

I would personally recommend second one, because that way the calculation of the array will be only once and will be used in all cases.