Hi all!
It seems to me that I find interesting bug in Yii.
In my ActiveRecord models I often use getters to get some value from related tables.
As example:
class Clients extends CActiveRecord{
//...
public function relations()
{
return array(
'regions' => array(self::BELONGS_TO, 'Regions', 'habitation_regions_id'),
);
}
//...
public function getRegion()
{
return $this->regions->title;
}
}
Then, somwhere in my views:
//view file admin.php
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'client-grid',
'cssFile'=>Yii::app()->baseURL.'/css/MyGridview.css',
'rowCssClass'=>array('row0', 'row1'),
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
array(
'class'=>'CCheckBoxColumn',
'selectableRows'=>2,
),
array(
'name'=>'fullname',
'value'=>'$data->fullname',
'filter'=>'',
),
array(
'name' => 'region',
'value' => '$data->region',//method getRegion() in my Clients model
'filter'=> CHtml::listData(Regions::model()->findAll(), 'id', 'title')
),
),
)); ?>
Code of controller’s action:
//ClientController.php
public function actionAdmin()
{
$this->layout = '//layouts/column1';
$model = new Clients('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['Client'])){
$model->attributes = $_GET['Client'];
}
$this->render('admin', array('model' => $model));
}
Then, when I call URL http://myhost/myapplication/index.php?r=client/admin, it calls Exception, which says “Trying to get property of non-object” about my method getRegion() in model Clients.php. Field ‘habitation_regions_id’ is not empty and it’s values a valid. I tried to redeclare my getRegion() method in such way:
//Clients.php model
public function getRegion()
{
return Regions::model()->findByPk($this->habitation_regions_id)->title;
}
It returns the same error - trying to get property of non-object (‘value’=>’$data->region’ in my admin.php view in CGridView column)
So, I began to try any variants to understand error:
public function getRegion()
{
return $this->regions->title; //the same error
}
I tried such variant:
public function getRegion()
{
return getttype(Regions::model()->findByPk($this->habitation_regions_id))//returns 'object'!
}
So, if it’s object, why it says ‘trying to get property of non-object’ ?
At last, I tried such variant:
public function getRegion()
{
$region_model = Regions::model()->findByPk($this->habitation_regions_id);
return $region_model['title'];
}
You know what? It works! I can get propertie of the object as element of array, but cannot get propertie of object as property of object! I know that CActiveRecord eventually implements IteratorAggregate and ArrayAccess interfaces, but they both must works. What do you think about it?