How to use model object in Yii Controller and View

荒凉一梦 提交于 2019-12-25 17:16:09

问题


I have following method:

public function actionIndex() {

        $companyModel = Company::model()->findAll();          
        $supplierProductModel = SupplierProduct::model()->findAll();

        $this->render('index', array(
            'companyData' => $companyModel,
            'supplierProductData' => $supplierProductModel,
        ));
    }

Here I have passed model objects to render function and want to access these objects in view (Active Relational Type) but when I am accessing its in view its showing error:

Trying to get property of non-object 

view file (index.php)

echo $companyData->name . "\n";
echo $this->companyModel->phone . "\n";
echo $this->companyModel->fax . "\n";
echo $this->companyModel->cell . "\n";

Any help would be appreciated.


回答1:


you need to declare $this->companyModel in your controller/action

$this->companyModel = Company::model()->findByPk($companyId);

with Company::model()->findAll() you get an array of Company-Models you can iterate over in your view-file.

foreach ($companyData as $companyModel) {
    var_dump($companyModel->attributes);
}



回答2:


It is happening becoz of findAll()

findAll() reruns all rows of company table in multidimensional array, so here $companyData is multidimensional Array, now change your code in index like bellow,

        <?php
        foreach ($companyData as $compSub)
        {
            echo $compSub->name . "\n";
            echo $compSub->phone . "\n";
            echo $compSub->fax . "\n";
            echo $compSub->cell . "\n";
        }
        ?>

If you want a company data(single row), change your query like this

         $companyModel = Company::model()->findByPk($id_Of_company); 
         //$companyModel is single dimensional array, it has all the info of a company. 

Send this to view

        $this->render('index', array(
        'companyData' => $companyModel,
        ....................
        ));

Now you can show the data using bellow code

        echo $companyData->name . "\n";
        echo $companyData->phone . "\n";
        echo $companyData->fax . "\n";
        echo $companyData->cell . "\n";



回答3:


You are trying to get all the entries from the database as findAll() returns all data in multidimensional array of objects.If you need all the entries you could iterate over it in the view file and get the results as shown

In the View File do as shown

<?php foreach($companyData as $value){
  echo $vlaue->name . "\n";
  echo $value->phone . "\n";
  echo $value->fax . "\n";
  echo $value->cell . "\n";
 ?>

With this you get all the entries from the table

If you want to get a particular record use condition using Cdbcriteria and pass the object and get the single result



来源:https://stackoverflow.com/questions/17522163/how-to-use-model-object-in-yii-controller-and-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!