0

在我的 SiteController.php

public function actionIndex()
{
    // renders the view file 'protected/views/site/index.php'
    // using the default layout 'protected/views/layouts/main.php'
    //$this->render('index');

    $dataProviderUser=new CActiveDataProvider('User',array(
                'pagination'=>array(
                    'pageSize'=>20,
                ),
            ));
    $dataProviderDomain = new CActiveDataProvider('Domain');

    $this->render('index',array(
    'dataProvider1'=>$dataProviderUser,
    'dataProvider2'=>$dataProviderDomain
    ));
}

在我的主题/k/views/layout/main.php

        <?php 
        if(!Yii::app()->user->isGuest)
        {
        $this->widget('zii.widgets.CListView', array(
            'dataProvider'=>$dataProvider2,
            'itemView'=>'_view',));
        ?>

出现这个错误:未定义变量:dataProvider2

如果我在我的 main.php 中这样做:

<?php 
        $dataProvider2 = new CActiveDataProvider('Domain');
        if(!Yii::app()->user->isGuest)
        {
        $this->widget('zii.widgets.CListView', array(
            'dataProvider'=>$dataProvider2,
            'itemView'=>'_view',));
        ?>

到目前为止效果很好。但是如果我去用户配置文件:

/user/view/id/5

未定义属性“Domain.username”。

所以在我的 User _view.php 中 Yii 似乎采用了 Domain Dataprovider。

如何将这些 dataProviders 传递到我的布局 main.php 文件? SiteController.php 似乎没有做到这一点。

如果有人在这里有想法,那就太好了。先谢谢了。

4

1 回答 1

1

Variables that you have defined in your controller action are only available to immediate view files that are being used to render a view. They are not available to layouts. However, layouts will be able to use public methods and properties of the controller. So, if you want to pass a variable to your layout you need to declare it as a property of the controller. There are two ways of doing this.

Firstly, you can just create a public variable.

Class YourController extends CController{

public $dataProvider2;

public function actionIndex(){
// renders the view file 'protected/views/site/index.php'
    // using the default layout 'protected/views/layouts/main.php'
    //$this->render('index');

    $dataProviderUser=new CActiveDataProvider('User',array(
                'pagination'=>array(
                    'pageSize'=>20,
                ),
            ));
    $dataProviderDomain = new CActiveDataProvider('Domain');

//Added new line here
$this->dataProvider2 = $dataProviderDomain;
    $this->render('index',array(
    'dataProvider1'=>$dataProviderUser,
    'dataProvider2'=>$dataProviderDomain
    ));
}

}

$this->dataProvider is now available in your view file, but don't foorget to check that it exists before using it.

The other method is to use the magic getter method from Yii.

In your model, describe a method like this;

public function getdataProvider2(){
return $this->_dataProvider2;
}

and you'll need a property;

private $_dataProvider2;
于 2013-12-09T11:42:47.693 回答