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 :

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 ));

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

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

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