Widget creation in Yii – Basic workflow

Widget creation in Yii – Basic workflow

Posted by: Sharath K Mohan
Category :Free & Open Source

Yii is a secure, fast and professional Php framework, which follows M.V.C. based design pattern. The main features of Yii are authentication, access control, automated-code generation (through gii tool), jQuery – AJAX support, Theming, Caching, etc. This blog chronicles my experiences in creating a simple Yii widget.

What is a Yii widget?

A widget in Yii is a part of a view that renders the data and works based on some kind of logic. It can also get data from the models and use its own views, so it is like a reduced reusable version of a module.
Main points to remember while creating a widget:

  1. Extend CinputWidget:
    A widget class has to extend CinputWidget, which is the base class for widgets that accepts the user inputs. The child classes of CinputWidget may use resolveNameID (for getting the name and ID of the input) and hasModel (to check if the widget is associated with the model).
  2. Initialize the init and run methods:

    init is used to initialize any actions like declarations or overriding. It is invoked on calling $this->beginWidget in the view and run is invoked when $this->endWidget is being called.

  3. Register the resources:

    A widget might be dependent on various css, javascript and other resource files. All these are packed together and are called assets of the widget. All the assets of the widget are published using the CWebApplication::assetManager

  4. Pass the attributes for the widget from the view file:

    A widget may or may not have body content.

    Each of the properties can be accessed by the widget in the widget class, under the same name.

    If the properties are to be passed to a script file then they have to be encoded using the CjavaScript::encode($this->). The CjavaScript::encode, encodes a Php variable into javascript representation.

Application structure for an extension (widget)

Yii app root > protected > extensions > {name of your widget} > {Widget class + Assets > {scripts + css + other resources}}.

Here is an image of an editor widget in a view file.

These are the steps that you have to follow to create a widget in Yii.

More info
Refer for more details regarding creating an extension in Yii.

Leave a Comment

Your email address will not be published.