Question

Guys help me to do this. I'm new to YII. I want to display each item branches stock like this.

enter image description here

actual database

enter image description here

What is the best way to do this?

Was it helpful?

Solution

What you are looking for is a cross tab or pivot table. Here is a link: http://www.artfulsoftware.com/infotree/qrytip.php?id=523

OTHER TIPS

I have been looking for the same thing and have a solution using CSqlDataProvider. It is important to note when using CSqlDataProvider it returns an array unlike CActiveDataProvider which returns an object.

Here is the model code

public function displayStock($id)
{
    $sql='SELECT product_id, COUNT(*) as productCount FROM stock WHERE assigned_to = 2 GROUP BY product_id';
    $dataProvider=new CSqlDataProvider($sql, array(


        'pagination'=>array(
            'pageSize'=>10,
        ),
    ));
    return $dataProvider;
}

Here is the code for the veiw

$stockDataProvider = Stock::model()->displayStock(Yii::app()->user->id);
$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'stock-grid',
    'ajaxUpdate' => true,
    'template'=>'{items}{summary}{pager}',
    'dataProvider'=>$stockDataProvider,
    'columns'=>array(

        'product_id',
        array(
                'name'=>'test',
                'value'=>'$data["productCount"]'
            ),


        array(
            'class' => 'CButtonColumn',
            'template' => '{view} {update}',

        ),

    ),
));

When defining the SQL statement in the model, you can see we have set the COUNT(*) to be called productCount. Then in the view we reference that name in the columns array like so

array(
                'name'=>'test',
                'value'=>'$data["productCount"]'
            ),

So simply replace productCount with the name you have used.

I'm sure the above code could do with some tweaking ie using Binded params in the query etc, but this has worked for me.

Any comments or improvements are very welcome. I'm only about 8 months into php and 3 months into yii.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top