在静态调用的方法中使用小部件 [英] Use a widget in a statically-called method
问题描述
通常通过在 CController
的实例上调用 CController::widget()
来使用小部件,通常是在视图中的 $this
.
Normally a widget is used by calling CController::widget()
on an instance of CController
, typically $this
in a view.
但是如果我正在编写一个静态方法,比如一个助手,那么我就无法访问 CController
的实例.那么如何使用小部件?
But if I'm writing a static method, a helper, say, then I don't have access to an instance of CController
. So how do I use a widget?
让我们进一步说,这个辅助方法是在 CDataColumn
的 value
属性中的 eval()
表达式中调用的.那种糟糕的表达几乎没有任何背景.助手应该如何使用小部件?
Let's say further that this helper method is invoked in the eval()
’ed expression in a CDataColumn
's value
property. That poor expression has almost no context at all. How should the helper use a widget?
根据要求,视图示例:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(),
'columns' => array(
array(
'name' => 'attrName',
'value' => '--USE WIDGET HERE--',
),
)
));
推荐答案
这个答案没有回答一般的问题,而是在特定情况下——如何访问控制器并在计算表达式的上下文中使用小部件CDataColumn::$value
——你可以使用这个:
This answer doesn't answer the question in general but in the specific case—how to access the controller and use a widget in the context of the evaluated expression of CDataColumn::$value
—you can use this:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(),
'columns' => array(
array(
'name' => 'attrName',
'value' => function ($data, $row, $column) {
$controller = $column->grid->owner;
$controller->widget(/* ... etc ... */);
},
),
)
));
诀窍是发现 CDataColumn::renderDataCellContent()
使用 CComponent::evaluateExpression()
,它将组件实例作为最后一个参数注入回调.在这种情况下,组件是 CDataColumn
,它引用控制器,如图所示.
The trick was discovering that CDataColumn::renderDataCellContent()
uses CComponent::evaluateExpression()
, which injects the component instance into the callback as the last parameter. In this case that omponent is the CDataColumn
, which references the controller as shown.
我不喜欢将 PHP 表达式写为字符串文字,所以我很高兴找到这个选项.
I don't like writing PHP expressions as string literals so I'm pleased to find this option.
对http://www.yiiframework.com/doc/api/1.1/的评论CDataColumn#value-detail 向我们展示了我尚未尝试过的列值中的小部件的另一种方法.
A comment on http://www.yiiframework.com/doc/api/1.1/CDataColumn#value-detail shows another way to us a widget in a column value that I haven't tried.
这篇关于在静态调用的方法中使用小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!