How to create a custom widget in Yii?

by elise_daugherty , in category: PHP Frameworks , 2 months ago

How to create a custom widget in Yii?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 12 days ago

@elise_daugherty 

To create a custom widget in Yii, follow these steps:

  1. Create a new directory in the protected/widgets directory within your Yii application. The name of the directory should be the name of your widget.
  2. Create a new PHP file within the newly created directory. This file will contain the code for your new widget.
  3. Define your widget class within the PHP file. The class should extend the CWidget class and contain any properties and/or methods specific to your widget.
  4. Within the class, implement the run() method. This method will be called when the widget is rendered and should contain the HTML that will be displayed.
  5. Optionally, you can define parameters that can be passed to the widget when it is instantiated. To do this, define a public property for each parameter and use the init() method to set default values.
  6. Once your widget code is complete, you can use it in your views by calling the widget() method and passing the name of your widget class as an argument.


Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// in protected/widgets/MyWidget/MyWidget.php
class MyWidget extends CWidget
{
    public $title;
    public $content;

    public function init()
    {
        if($this->title === null)
            $this->title = 'Default Title';
    }

    public function run()
    {
        echo '<h2>'.$this->title.'</h2>';
        echo '<p>'.$this->content.'</p>';
    }
}

// in your view file
$this->widget('application.widgets.MyWidget.MyWidget', array(
    'title'=>'My Custom Widget',
    'content'=>'Hello, World!'
));