問(wèn)題描述
我的教師模型中有一個(gè)函數(shù)返回類別數(shù)組.
I have a function in my Teacher model which returns categories array.
getCaterogies() {
return array('1' => 'short tempered', '2' => 'funny', '3' => 'visionary', ...);
}
我將索引存儲(chǔ)在數(shù)據(jù)庫(kù)中,并使用對(duì)應(yīng)于該數(shù)組的值在各處顯示值..
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];
我這樣做是因?yàn)橛幸淮斡腥私ㄗh我不要在數(shù)據(jù)庫(kù)中存儲(chǔ)狀態(tài)字符串,而是存儲(chǔ)整數(shù)值,并將轉(zhuǎn)換存儲(chǔ)在數(shù)據(jù)庫(kù)中或在 ht 模型中定義它.字符串的問(wèn)題在于它們?cè)诒容^中更容易出現(xiàn)人為錯(cuò)誤.可能是因?yàn)閰^(qū)分大小寫.
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.
現(xiàn)在我面臨的問(wèn)題是,在 gridview 中顯示值時(shí),我需要在值字段中寫入 2 行,但它是一個(gè)表達(dá)式,并且不需要外部變量.
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?
推薦答案
你可以使用匿名函數(shù)作為值,它可以接受 $row
, $data
params where $row
保存行號(hào)(從零開始),$data
包含行的數(shù)據(jù)模型.
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.
這樣你就可以只在內(nèi)部定義它.
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];
},
),
),
));
我個(gè)人推薦第二個(gè),因?yàn)檫@樣數(shù)組的計(jì)算將只進(jìn)行一次,并且會(huì)在所有情況下使用.
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.
這篇關(guān)于Yii gridview 在值中使用外部變量的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!