Let me see
Let me see

Reputation: 5094

How to show the the values of array in cgridview in yii

I am using yii and i want to display the results of an array in the cgridview The Cgridview code says

$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'users-grid',

    'dataProvider'=>$dataProviderObj,
    //'filter'=>$model,
    'columns'=>array(
    'companyName',
        array(
            'header'=>'Products',
            'value'=>'$data->usersproducts',
                ),

Now usersproducts is the relation name that maintains the many to many relation btween visitors and products

Generally if i want to get the data from $data->usersproducts i will do this

foreach($data->usersproducts as $record)
{
echo $record->productName;
}

But i dnt know how to get this data in cgrid view as foreach will not work in the CGridView array?

I know that i can use ($this,functionName) and return the result but i want to do it in the array only. Is it possible? and if so how can i do it?

Upvotes: 1

Views: 3097

Answers (1)

Keilo
Keilo

Reputation: 986

On your $data object, create a method to fetch all product names as you have described.

public function getUserProductNames()
{
    $ret = "";
    $first = true;

    foreach ($this->userproducts as $record) {

        if ($first === true) {
            $first = false;
        } else {
            $ret .= ', ';
        }

        $ret .= $record->productName;
    }

    return $ret;
}

Then in your CGridView configuration you can use:

'value'=>'$data->getUserProductNames()'

Upvotes: 5

Related Questions