Friday, 6 December 2013

Yii: Widget example and common errors

Widget is a flexible structure in yii. So how and where it can be used ?

Intended use : 

Create static blocks such as : header, footer, menu, sidebar blocks (other post, contact, ...)

Simple header widget example: 

Directory structure :
-Protected
---widgets
-----header
-------header.php
-------views
---------headerView.php
...

header.php
<?php
class header extends CWidget { //class must be same with file name and extended CWidget class
    public function init() {
            // do something
    }
    
    public function run() {
        //do something ...
        $model = Model::model()->findAll();
        $this->render('headerView',array('model'=>$model ));
    }
}
?>

headerView.php
<div id="topHeader">
          <!-- header content -->
          <?php var_dump($model); ?>
</div>

Using in layout :
<!DOCTYPE html>
<html dir="ltr" lang="en"> 
          <head>
          </head>
          <body>                  
                   <?php $this->widget('application.widgets.header.header'); ?>
                   <?php echo $content; ?>
          </body>
</html>

Common errors:

 "include(header.php): failed to open stream: No such file or directory"

How to solve :
1. Check alias path : "'application.widgets.header.header'" make it correct
2. Check class name in file header.php : make sure that it is same with file name.
3. Check other logic

0 nhận xét:

Post a Comment