Yii gridview use outside variable in value(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.
这篇关于Yii gridview 在值中使用外部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Yii gridview 在值中使用外部变量
基础教程推荐
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- 在多维数组中查找最大值 2021-01-01