Yii CGridview sorting with CSqlDataProvider - php

I'm using CSqlDataProvider to construct CGridview I cannot use CActiveRecord because the result set is huge and throwing memory errors. The columns need to be sortable. How should I achieve this?
Sample sql
$orders_query_raw = 'select o.order_id, o.customer_name, o.customer_email, o.customer_advertiser, o.payment_method, o.created, o.last_updated, o.currency, o.currency_value, o.status, o.blinking, s.name, ot.text order_total, o.customer_id, op.product_id, o.phonebooking
from `order` o, `order_total` ot, `order_status` s , order_product op
where o.order_id = op.order_id and o.status = s.order_status_id and ot.order_id = o.order_id and s.language_id = '1' and ot.class = 'ot_total' group by o.order_id'
sql dataprovider
$dataProvider = new CSqlDataProvider($orders_query_raw, array(
'totalItemCount'=>$count, // get from a count query
'pagination'=>array(
'pageSize'=>50,
),
));
And gridview
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $dataProvider,
'id'=>'order-grid',
'columns' => array(
array(
'header'=>'Order ID',
'value'=>array($this, 'gridOrderId'),
'type'=>'raw',
),
array(
'header'=>Yii::t('order', 'Customers'),
'name'=>'customer.fullName',
'value'=>'CHtml::link($data[\'customer_name\'], \'mailto:\'.$data[\'customer_email\'])',
'type'=>'raw',
),
array(
'header'=>Yii::t('order', 'Order total'),
'value'=>'strip_tags($data[\'order_total\'])',
'type'=>'raw',
'htmlOptions'=>array(
'style'=>'text-align:right;',
),
),
array(
'header' => Yii::t('order', 'Date Purchased'),
'name' => 'created',
),
array(
'header'=> Yii::t('order', 'Last modify date'),
'value'=>array($this, 'gridLastModified'),
),
array(
'header' => Yii::t('order', 'Status changed by'),
'value' => array($this, 'gridLastModifiedUserFirstName'),
),
array(
'header' => Yii::t('provider', 'Provider\'s code'),
'value' => array($this, 'gridProviderCode'),
'type' => 'raw',
'htmlOptions'=>array(
'class'=>'nobr',
),
),
array(
'header' => Yii::t('order', 'Follow up'),
'value' => array($this, 'gridFollowUp'),
'type' => 'raw',
),
array(
'header' => Yii::t('order', 'Order status'),
'value' => '$data[\'name\']',
),
array(
'class'=>'CButtonColumn',
'template'=>'{update}',
'header'=>'Action',
'buttons'=>array(
'update'=>array(
'url'=>'Yii::app()->createUrl(\'order/update\', array(\'order_id\'=>$data[\'order_id\']))',
),
),
),
),
));
Thanks

To enable sorting (by clicking on header of a column) in the grid-view with data provider as CSqlDataProvider, you'll need minimally 2 things:
Have to define the CSort object for the data provider, with the attributes that would be sortable.
Have to define the name of the column but only in case you are specifying the columns property of the grid-view, otherwise if the columns property is left blank, whatever attributes are mentioned in the CSort object will be sortable.
That said, the other answer should work in cases when the sql is simple, and comes from 1 table, but in your case, where the sql is a little complicated i.e data comes from multiple tables, the solution will change slightly.
In such cases you'll have to account for conflicting column names(if any), and proper specification of CSort's attributes array.
Examples:
No conflicting column names in any of the tables (same as the other answer):
$dataProvider=new CSqlDataProvider($sql, array(
'totalItemCount'=>$count,
'sort'=>array(
'attributes'=>array(
'order_id, order_total' // csv of sortable column names
)
)
));
Then in your grid:
array(
'header'=>Yii::t('order', 'Order total'),
'name'=>'order_total',// to make header clickable to sort
'value'=>'strip_tags($data[\'order_total\'])',
'type'=>'raw',
'htmlOptions'=>array(
'style'=>'text-align:right;',
),
),
Conflicting column names:
First, give all conflicting names aliases in your sql.
Second, specify those aliases as the sortable attributes in the CSort object:
'attributes'=>array(
'some_alias, some_other_alias'
)
Specify the name for the column in columns:
array(
'header'=>'Foo',
'name'=>'some_alias',
'value'=>'$data[\'some_alias\']' // this is actually redundant in this
// case, because the name will itself pick up the value, and we don't
// need to specify value explicitly if we are not applying any function to it
)
Note that sorting by url calling is enabled by just specifying the sort object, no need to use name, unless you want click to sort headers.

Try as below
$sort = new CSort();
$sort->defaultOrder = 'order_id'; // for initial order
$sort->attributes = array(
'created'
);
$dataProvider = new CSqlDataProvider($orders_query_raw, array(
'totalItemCount'=>$count, // get from a count query
'pagination'=>array(
'pageSize'=>50,
),
'sort'=>$sort
));

Related

Yii Framework Undefined Offset: 0

I am trying to use CGridView with custom query, and trying to build a very simple with no sorting and stuff.
My View contains simple CGridView
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
));
And my controller passes the $dataProvider to the view
$count=Yii::app()->db->createCommand('SELECT COUNT(*) FROM ( ' . $query . ' ) as count')->queryScalar();
$dataProvider=new CSqlDataProvider($query, array(
'keyField' => false,
'totalItemCount'=>$count,
'pagination'=>array(
'pageSize'=>10,
),
));
I don't have a keyField therefore I have set it to false. Moreover, I have tried printing out data using var_dump, data is present in the variable, but still I get this undefined offset error.
You need to set the mapping for sorting.
/*
Query results
array(
array(
'id' => 1,
'username' => 'username',
'email' => 'email'
),
...
)
*/
return new CSqlDataProvider($query, array(
'keyField' => 'id', //required, any field from query results
'totalItemCount'=> $count,
'pagination' => array(
'pageSize' => 10
),
'sort' => array(
'defaultOrder' => array(
'username' => CSort::SORT_DESC,
),
'attributes' => array(
'username',
'email',
),
),
));
//grid.columns
array(
array(
'name' => 'id' //WO sort
),
array(
'name' => 'username', //with sort (isset in dp.sort.attributes)
),
)
you have to provide keyfield other than false, change keyfield primary key of your query Table

Yii Booster Gridview table joining table

i want to create a table like this Yii Booster Gridview table
here is my code in controller:
$rawData=Jobspecs::model()->with('customer')->findAll();
$gridDataProvider=new CArrayDataProvider($rawData, array(
'id'=>'user',
'sort'=>array(
'attributes'=>array(
'id', 'customer',
),
),
));
$gridColumns = array(
array('name'=>'id', 'header'=>'Js No.', 'htmlOptions'=>array('style'=>'width: 60px')),
array('name'=>'WHAT TO PUT HERE TO SHOW CUSTOMER NAME', 'header'=>'Customer Name'),
array(
'htmlOptions' => array('nowrap'=>'nowrap'),
'class'=>'booster.widgets.TbButtonColumn',
'viewButtonUrl'=>null,
)
);
in my model sapcustomers:
return array(
'customer'=>array(self::BELONGS_TO, 'Sapcustomers', 'customer'),
);
jobspecs model
return array(
'cardname'=>array( self::HAS_MANY, 'Jobspecs', 'customer' ),
);
my view
<?php
$this->widget(
'booster.widgets.TbGridView',
array(
'type' => 'bordered',
'dataProvider' => $gridDataProvider,
'template' => "{items}",
'columns' => $gridColumns,
)
);
?>
as you can see i joined sapcustomers and jobspecs table. my question is what code i need to put on the $gridcolums to show the customer name data from the table sapcustomer. thanks for the help
I think this should work for you:
$gridColumns = array(
[...]
array(
'name'=>'customer',
'value'=>'$data->customer->name',
'header'=>'Customer Name'
),
);
Explanation
The $data stands for the Jobspecs-model from the actual row. Then you access the related customer and his name.

How create sort option for Yii gridview custome column fields

I want do sort for custome column fields for table fields its working fine, clinkcolumn fields or customs fields not working
<?php
$this->widget('zii.widgets.grid.CGridView',
array(
'dataProvider'=>$dataProviderInActive,
'id'=>'collections-grid-inactive',
'itemsCssClass'=>'table collections',
'ajaxUpdate'=>true,
'pager'=>array(
'class'=>'CLinkPager',
'header'=>'',
),
'columns'=>array
(
array(
'class'=>'CLinkColumn',
'labelExpression'=>'$data->collection_title',
'urlExpression'=>'Yii::app()->createUrl("",array("collection"=>$data->collection_title))',
'header'=>'Catalog Title'
),
array( // display 'author.username' using an expression
'name'=>'Number of Images',
'value'=>'',
),
array( // display 'author.username' using an expression
'name'=>'Number of images used in lightboxes',
'value'=>'0',
),
array( // display 'author.username' using an expression
'name'=>'Number of expired',
'value'=>'0',
),
array( // display 'create_time' using an expression
'name'=>'Date Created',
'value'=>'date("Y-m-d", $data->created_at)',
),
array( // display a column with "view", "update" and "delete" buttons
'class'=>'CButtonColumn',
'template'=>'{view}{edit}{delete}{expiration_report}',
'buttons'=>array
(
'view' => array
(
'label'=>'view',
'options'=>array('class'=>'btn'),
'imageUrl'=>'',
'url'=>'Yii::app()->createUrl("",array("collection"=>$data->collection_title))',
),
'edit' => array
(
'label'=>'edit',
'options'=>array('class'=>'btn'),
'imageUrl'=>'',
'url'=>'Yii::app()->createUrl("", array())'
),
'delete' => array
(
'label'=>'delete',
'options'=>array('class'=>'btn-danger btn'),
'imageUrl'=>'',
'url'=>'Yii::app()->createUrl("", array())'
),
'expiration_report' => array
(
'label'=>'expiration report',
'options'=>array('class'=>'btn'),'imageUrl'=>'',
'url'=>'Yii::app()->createUrl("", array())'
),
)
),
),
));
?>
Try adding the attribute in the sort attributes array:
$dataProviderInActive->sort->attributes['collection_title']=array(
'asc'=>'collection_title',
'desc'=>'collection_title DESC');
Your question doesn't have the full details. If this is a custom field, you will have to explicitly define the sorting based on the object type. For example, I did this for CArrayDataProvider objects, and here it is. You will need to do this in your model. Again, the answer will depend on the object type. In my example, $rawData was the returned data from a database query.
return new CArrayDataProvider($rawData, array(
'id'=>'id',
'sort'=>array(
'attributes'=>array(
'attribute1',
'attribute2',
),
),
'pagination'=>array(
'pageSize'=>50,
),
));

Sorting columns with CGridView in Yii based on function call in value

I have these codes in my view file:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'name' => 'Name',
'type'=>'raw',
'value' => 'CHtml::link(CHtml::encode($data->profile->first_name." ".$data->profile->last_name),array("match/view","id"=>$data->id))',
),
array(
'name' => 'Similiarity Score',
'type'=>'raw',
'value' => array($this, 'calculateScore'),
),
),
)); ?>
You will notice that the second column call the function calculateScore($data, $row) in the controller file. Is there anyway I can sort the table based on these scores?
I assume that your result is from a database and you use a CActiveDataProvider or CSqlDataProvider. In this case you will have to move the logic for calculateScore into the DB query somehow. You can add a public property score to your model class and add this to the select property of your CDbCriteria:
$criteria->select = array('*', '... SQL FOR SCORE CALC HERE ... AS score');
Then you will be able to sort by that score in the sort definition of your CActiveDataProvider:
'sort' => array(
'attributes' => array(
// ...
'score',

How to change the sequence of 'joins' in CakePHP?

I have the problem with the sequence of joins. The similar problem was in another question Manipulating Order of JOINS in CakePHP. The answer was to use Containable behavior. In my case that is unacceptable because I have deeper associations and containable generates too many queries. Containable does not generate joins for the three level associations. It generates additional queries for every entry from the second level table.
My query is:
$this->LevelOne->find('all', array(
'joins' => array(array(
'table' => 'level_three',
'alias' => 'LevelThree',
'type' => 'LEFT',
'conditions' => array(
'LevelThree.id = LevelTwo.level_three_field_id'
)
))
));
The problem here is that cake generates several joins but the join of the LevelThree table is done before the joins of the LevelTwo tables and that throws an SQL error "Unknown column 'LevelTwo.level_three_field_id' in 'on clause'". If the LevelThree join would be at the end of the query after all LevelTwo joins the query would be okay.
So, the question is how to change the sequence of joins?
Finally I figured out how to do that:
$this->LevelOne->unbindModel(array('belongsTo' => array('LevelTwo')));
$this->LevelOne->find('all', array(
'joins' => array(
array(
'table' => 'level_two',
'alias' => 'LevelTwo',
'type' => 'LEFT',
'conditions' => array(
'LevelTwo.id = LevelOne.level_two_field_id'
)
),
array(
'table' => 'level_three',
'alias' => 'LevelThree',
'type' => 'LEFT',
'conditions' => array(
'LevelThree.id = LevelTwo.level_three_field_id'
)
)
)
));
To those who has similar problems but in relations a-la $belongsTo, to have correct order you should set it correctly.
For example when you have such code:
var $belongsTo = array(
'Vacancy',
'Applicant' => array(
'className' => 'Person',
),
'Recruiter' => array(
'className' => 'Person',
),
'Company' => array(
'conditions' => array('Company.id = Vacancy.company_id'),
),
);
But in the result always receive results where Vacancy always joins last, you should do juts simple thing: add those "Vacancy" model not as array value, but as a key=>value, as others:
var $belongsTo = array(
'Vacancy' => array(), // Just add empty array here -- all magic is here :)
'Applicant' => array(
'className' => 'Person',
),
'Recruiter' => array(
'className' => 'Person',
),
'Company' => array(
'conditions' => array('Company.id = Vacancy.company_id'),
),
);
Now all will be in straight order: Vacancy, Applicant, Recruiter & only then Company.
Have you thought about creating a HABTM model and inserting your own 'finderQuery' to override the model query?
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
Sometimes with complex queries, it make more sense to create the custom query so cake doesn't have to deal with it. To do that, you can just create the function in the model and then call it like you would any other query.
function customJoin(){
return $this->query('CUSTOM QUERY HERE');
}
Then call it from the controller:
$this->ModelName->customJoin();
I think sometimes we rely too heavily on the automation that a framework provides and forget that WE are in control and can implement code outside of the core. I do it all the time. Hope this helps.
public function selectdata(){
$option= $this->Group->find('all',
array(
'joins' =>
array(
array(
'table'=> 'user_groups',
'alias'=>'g',
'type'=> 'INNER',
'conditions'=> array('g.group_id =Group.id ')
),
array(
'table'=> 'users',
'alias'=>'u',
'type'=> 'INNER',
'conditions'=> array('u.id = g.user_id')
),
),'fields'=>array('Group.name,Group.created,Group.modified,Group.status,Group.created_by,u.first_name,u.last_name'),
'conditions'=>array('g.group_id=Group.created_by or g.user_id=u.id')
// ."'".$created_by."'"
)
);
var_dump($option);//die();
if(isset($this->params['requested']))
{
return $option;
}
$this->set('groups', $option);
}

Categories