Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use a widget in a statically-called method

Tags:

widget

yii

Normally a widget is used by calling CController::widget() on an instance of CController, typically $this in a view.

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?

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?


EDIT: Code example

As requested, a view example:

$this->widget('zii.widgets.grid.CGridView', array(
    'dataProvider' => $model->search(),
    'columns' => array(
        array(
            'name' => 'attrName',
            'value' => '--USE WIDGET HERE--',
        ),
    )
));

2 Answers

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 ... */);
            }, 
        ),
   )
));

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.

I don't like writing PHP expressions as string literals so I'm pleased to find this option.

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.

This one is working solution for calling widgets in static methods in Yii

Yii::app()->controller->widget('widget');
like image 22
Stas Panyukov Avatar answered Dec 02 '25 04:12

Stas Panyukov