How to complete data provided by a CActiveRecord model in Yii?

76 views Asked by At

I'm working on a Yii 1.1.16 application and have following difficulty:

There is a model FooModel based on the CActiveRecord. Behind it is a database table bar_table with a very inconvenient data structure:

id: integer
some_column: string
data: string <- JSON

That means, I get almost the whole data as a JSON string. (Yes, it's crazy, but now I accept it as given.)

In the view the data should get passed to CGridView widget and shown as a table. That means, I have to modify the data, in order to display it.

I see to possibilities / places to do that:

  1. On the model layer, probably in the model class. Then the widget will get the modified data and process it as usual.
  2. On the view layer, probably in the view file. Then I'll have to modifiy the data I got from the model and pass it somehow to the widget.

What is the better approach (or maybe there is a much more elegant one and how to implement it?

2

There are 2 answers

0
automatix On

Here is a an ugly solution (ugly because a public property is used), anyway it works:

model class Foo

class Foo extends CActiveRecord {
    ...
    public $buz;
    ...
    public function findAll($condition, $params=array()) {
        $resultData = parent::findAll($condition='', $params);
        foreach ($resultData as $key => $insuranceExternal) {
            $data = json_decode($insuranceExternal->getAttribute('data'), true);
            $insuranceExternal->setAttribute('myAdditionalProperty', $data['baz']['buz']);
        }
        return $resultData;
    }
}

view

$dataProvider = $model->search();
$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'my-grid',
    'dataProvider'=>$dataProvider,
    'filter'=>$model,
    'columns'=>array(
        ...
        'myAdditionalProperty',
    ),
));
0
TSchiffler On

you could use the "afterFind" method/event to handle your json data

class Foo extends CActiveRecord {

  protected function afterFind()
  {
     $this->data = json_decode($this->data);
  }