Servage Magazine

Information about YOUR hosting company – where we give you a clear picture of what we think and do!

Working with Widgets in Yii Framework

Wednesday, August 8th, 2012 by Servage

Widgets are a great tool in Yii to encapsulate recurring view logic and design into reusable elements, called Widgets. These widgets can be anything, like a sidebar-box, a menu, or whatever your application needs. The main concept and advantage of widgets is that you can build your code once, and reuse it wherever you need it in your view. Check out the below from The Ultimate Guide to Yii here:

A widget is an instance of CWidget or a child class of CWidget. It is a component that is mainly for presentational purposes. A widget is usually embedded in a view script to generate a complex, yet self-contained user interface. For example, a calendar widget can be used to render a complex calendar user interface. Widgets facilitate better reusability in user interface code.

To use a widget, do as follows in a view script:

<?php $this->beginWidget('path.to.WidgetClass'); ?>
...body content that may be captured by the widget...
<?php $this->endWidget(); ?>

or

<?php $this->widget('path.to.WidgetClass'); ?>

The latter is used when the widget does not need any body content.

Widgets can be configured to customize their behavior. This is done by setting their initial property values when calling CBaseController::beginWidget or CBaseController::widget. For example, when using a CMaskedTextField widget, we might like to specify the mask being used. We can do so by passing an array of initial property values as follows, where the array keys are property names and array values are the initial values of the corresponding widget properties:

<?php
$this->widget('CMaskedTextField',array(
    'mask'=>'99/99/9999'
));
?>

To define a new widget, extend CWidget and override its init() and run() methods:

class MyWidget extends CWidget
{
    public function init()
    {
        // this method is called by CController::beginWidget()
    }

    public function run()
    {
        // this method is called by CController::endWidget()
    }
}

Like a controller, a widget can also have its own view. By default, widget view files are located under the views subdirectory of the directory containing the widget class file. These views can be rendered by calling CWidget::render(), similar to that in controller. The only difference is that no layout will be applied to a widget view. Also, $this in the view refers to the widget instance instead of the controller instance.

Working with Widgets in Yii Framework, 3.7 out of 5 based on 7 ratings
Categories: Guides & Tutorials

Keywords:

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

No comments yet (leave a comment)

You are welcome to initiate a conversation about this blog entry.

Leave a comment

You must be logged in to post a comment.