Pirr
Pirr

Reputation: 123

how to display array to CGridView (yii framework)

I have next variables:

$type_model = ProductTypeModel::model()->findByPk($id);
$prod = $type_model->product;

Now in $prod:

array
(
    0 => ProductModel#1
    (
        [CActiveRecord:_new] => false
        [CActiveRecord:_attributes] => array
        (
            'product_id' => '6'
            'product_type_id' => '5'
        )
        ...
    )
    1 => ProductModel#2
    (
            'product_id' => '8'
            'product_type_id' => '5'
    )
    ...

How i can display my products in CGridView? Thx.

Upvotes: 1

Views: 1007

Answers (3)

Pirr
Pirr

Reputation: 123

Thanks all. By means of answers "naveen goyal" and "jailed abroad" i did like this:

$dataProvider=new CArrayDataProvider($type_model->product);
$dataProvider->keyField = 'product_id';
$this->widget('bootstrap.widgets.TbGridView', array(
    'dataProvider' => $dataProvider,
    'columns' => array(
        array(
            'header' => 'Title',
            'value' => 'CHtml::encode($data["product_title"])',
        ),

)));

Nice work for me.

Upvotes: 0

Rafay Zia Mir
Rafay Zia Mir

Reputation: 2116

I Suppose you are using CarrayDataProvider. So in your controller

$dataProvider = new CArrayDataProvider($prod);

Here $product could be any array you want to display in CgridView. Now In you view write this.

$gridColumns = array(
    array(
        'header' => 'First Name',
        'value' => 'ProductTypeModel::model()->findByPk($data->product_id)->key',
        'htmlOptions' => array('style' => 'text-align:center;')
    ),


$this->widget('zii.widgets.grid.CGridView',array('dataProvider' => $dataProvider,));

As in CarrayDataprovider array is obtained so we cant use relations in it. Thats why u have to write 'ProductTypeModel::model()->findByPk($data->product_id)->key'
Here you can display anything attribute of ProductTypeModel so u can replace above mentioned key with your desired attribute

Upvotes: 1

naveen goyal
naveen goyal

Reputation: 4629

Try this ... it automatic convert to array data provider.

$dataProvider=new CArrayDataProvider($type_model->product);

Upvotes: 0

Related Questions