davidhhuan 2012-01-09 10:55:00 4012次浏览 1条回复 0 0 0

Here is an example of how to develop a widget (yes, widget is also an extension in Yii) in Yii.

Let say you want to display something with widget in the page, of course you can place your widget in protected/components when there are one or two classes inside. But when there is a lot of them, it is hard for you to manage them. Therefore we will place them in protected/extensions. Here we will build the testWidget, the path will be protected/extensions/testWidget.

Structure:

| | | `~testWidget/
| | |   |~assets/
| | |   | |~css/
| | |   | | `-testWidget.css
| | |   | |~images/
| | |   | | `-loading.gif
| | |   | `~js/
| | |   |   `-testWidget.js
| | |   |~views/
| | |   | `-testWidget.php
| | |   `-testWidget.php
  1. Develop a widget class file: testWidget.php
<?php
class testWidget extends CWidget
{
    private $loadingImageUrl;

    public function init()
    {
        $assetsDir = dirname(__FILE__).'/assets';
        $cs = Yii::app()->getClientScript();
        $cs->registerCoreScript("jquery");
        
        // Publishing and registering JavaScript file
        $cs->registerScriptFile(
            Yii::app()->assetManager->publish(
                $assetsDir.'/js/testWidget.js'
            ),
            CClientScript::POS_END
        );
                
        // Publishing and registering CSS file
        $cs->registerCssFile(
            Yii::app()->assetManager->publish(
                $assetsDir.'/css/testWidget.css'
            )
        );
        
        // Publishing image
        $this->loadingImageUrl = Yii::app()->assetManager->publish(
            $assetsDir.'/images/loading.gif'
        );
    }


    public function run()
    {
        $this->render(
            'testWidget', 
            array(
                'loadingImageUrl' => $this->loadingImageUrl,
            )
        );
    }
}
  1. Develop the view file:
<?php echo 'Hello, world!';?>
  1. You can develop you testWidget.css and testWidget.js file.
  1. Use the new widget.
<?php $this->widget("ext.testWidget.testWidget")?>

Yes, that is a very simple widget extension, just a tutorial to show how to build one.

Have fun with Yii!

您需要登录后才可以回复。登录 | 立即注册