How to use model object in Yii Controller and View

J.K.A. picture J.K.A. · Jul 8, 2013 · Viewed 7.9k times · Source

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.

Answer

user1522899 picture user1522899 · Jul 8, 2013

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