如何在 Yii 中制作小部件


how to make widget in Yii

我想创建一个小部件,这是我所做的步骤:

  • 在文件夹 protected 中创建文件夹widgets
  • 在文件夹 widgets 中创建文件夹views
  • config/main.php中添加了这个:'application.widgets.*'
  • 这是widgets/Alert.php的代码:
class AlertWidget extends CWidget
{
    public $alert = null;
    private $_data = null;
    public function init()
    {
        $s = Yii::app()->session['userId'];
        $r = Requests::model()->findAll('idUser='.$s.' and confirm =0 and unconfirm=0 and cancel=0');
        $i=0;
        foreach($r as $x)
            $i++;
            if($i<=0)
                $alert=null;
            else
                $alert="(".$i.")";
        $this->_data = new CActiveDataProvider($alert);
    }
    public function run()
    {
        $this->render('alert', ['data' => $this->_data]);
    }
}
  • 这是widgets/views/alert.php的代码:
echo $data;
  • 这是我如何在视图中使用小部件的代码:
$this->widget('application.widgets.Alert');

最后我得到了这些错误:

( ! ) SCREAM: Error suppression ignored for
( ! ) Fatal error: Cannot redeclare class AlertWidget in C:'wamp'www'mediastore'protected'widgets'Alert.php on line 27
如果你

要使用$this->widget('application.widgets.Alert');访问小部件,那么小部件类名应该是Alert(如:public class Alert extends CWidget...(,文件名应该保持Alert.php