Yii gridview 在值中使用外部变量

2021-12-24 00:00:00 php yii gridview

我的教师模型中有一个函数返回类别数组.

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];

我这样做是因为有一次有人建议我不要在数据库中存储状态字符串,而是存储整数值,并将转换存储在数据库中或在 ht 模型中定义它.字符串的问题在于它们在比较中更容易出现人为错误.可能是因为区分大小写.

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.

现在我面临的问题是,在 gridview 中显示值时,我需要在值字段中写入 2 行,但它是一个表达式,并且不需要外部变量.

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.

我怎样才能让它为 gridview 工作?

How can I get this working for gridview?

推荐答案

你可以使用匿名函数作为值,它可以接受 $row, $data params where $row 保存行号(从零开始),$data 包含行的数据模型.

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];
            },
        ),
    ),
));

如果你想从外面使用它,你可以依靠PHP的use:

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.

相关文章