I wanna display the retrieved data i.e CSqlDataProvider in CGridView through Pagination..
and I retrieved data from table through CSqlDataProvider and shown in CGridView
but the problem is at Pagination part..
Firstly look at my Controller code..
$count = Yii::app()->db->createCommand('SELECT COUNT(familyid) FROM (' . $sql2 . ') as count_alias')->queryScalar();
$rawData = Yii::app()->db->createCommand($sql2);
$dataProviderRegSum = new CSqlDataProvider($rawData, array(
'keyField' => 'familyid',
// 'pagination'=>false,
/* 'pagination' => array(
'pageSize' => Yii::app()->user->getState( 'pageSize', Yii::app()->params[ 'defaultPageSize' ] ),PaymentTxnDate
), */
'pagination'=>array('pageSize'=>20),
'totalItemCount' => $count,
'sort'=>array(
//'defaultOrder' => 'CreatedDate desc',
'defaultOrder' => 'PaymentTxnDate asc',
'attributes'=>array(
'RegistrationID'=>array(
'asc'=>'familyid',
'desc'=>'familyid DESC',
),
'FirstName'=>array(
'asc'=>'firstname',
'desc'=>'firstname DESC',
),
'LastName'=>array(
'asc'=>'lastname',
'desc'=>'lastname DESC',
),
'CreatedDate'=>array(
'asc'=>'CreatedDate',
'desc'=>'CreatedDate DESC',
),
'EmailedDate'=>array(
'asc'=>'EamiledDate',
'desc'=>'EamiledDate DESC',
),
),),
));
and my view is as
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'family-record-grid',
'dataProvider'=>$arr[1],
'enableSorting' => false,
//'enablePagination'=>false,
'itemsCssClass'=>'tabchin',
'columns'=>
array(),
));
here $sql2 is my query....
$arr[1] is dataprovider that has sent from controller to view as array...
I have totlaItemCount value
and pageSize is 20
All is right but in the output the first 20 records are displaying its ok
but pagelinks i.e pagenumbers for pagination is not displaying at the bottom..
its been two days stuck for this error ..still didnt get solution
please help me anyone thanks for reading the stuff...
help needed..
Related
Background
I have used Gii Crud Generator with my "Category" model, and I want to modify the admin form.
I look inside "protected/views/Category/admin.php,
I found the table is render by a widget('zii.widgets.grid.CGridView'),
and it using a data Provider for it's data.
I suppose I can find some where to input the SQL query in the data Provider, but I don't understand about how's it works.
these is the code In the Model->relations(), but I don't know what to do next.
public function relations(){
return array(
'cateLang' => array(self::HAS_MANY, 'CategoryLang', 'cate_id')
);
}
where the data provider is generated :
public function search(){
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('status',$this->status,true);
$criteria->compare('createDate',$this->createDate,true);
$criteria->compare('updateDate',$this->updateDate,true);
$criteria->compare('remark',$this->remark,true);
return new CActiveDataProvider($this->with('cateLang'), array(
'criteria'=>$criteria,
));
}
Target
I want to add two more columns at the table of "protected/views/Category/admin.php,
which will show French Title & English Title of the row.
To get data in SQL, it will be :
SELECT
cate.id,
lang1.name as "FrenchTitle",
lang2.name as "EnglishTitle",
cate.updateDate,
cate.createDate,
cate.remark
FROM `category` cate
LEFT JOIN `categorylang` lang1
ON `lang1`.`cate_id` = `cate`.id
AND `lang1`.`lang_id`= 1
LEFT JOIN `categorylang` lang2
ON `lang2`.`cate_id` = `cate`.id
AND `lang2`.`lang_id`= 2
WHERE cate.status = 'live'
If I can done with data Provider, the CGridView parameter may be like this :
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'FrenchTitle',
'EnglishTitle',
'createDate',
'updateDate',
'remark',
array(
'class'=>'CButtonColumn',
),
),
));
You could try the following:
public function search(){
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('status',$this->status,true);
$criteria->compare('createDate',$this->createDate,true);
$criteria->compare('updateDate',$this->updateDate,true);
$criteria->compare('remark',$this->remark,true);
$criteria->with = array('cateLang' => array(
'condition' => 'cateLang.id = 1 OR cateLang.id = 2',
'order' => 'cateLang.id ASC'
));
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'category-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
array(
'name' => 'FrenchTitle'
'value' => '(isset($data->cateLang[0])) ? $data->cateLang[0]->name : "no Title"',
),
array(
'name' => 'EnglishTitle'
'value' => '(isset($data->cateLang[1])) ? $data->cateLang[1]->name : "no Title"',
),
'createDate',
'updateDate',
'remark',
array(
'class'=>'CButtonColumn',
),
),
));
In the search I specify that I want only cateLang object with the id 1 or 2 and then in the cgridview I display a relational object.
I have simple CGridView, which is not showing me any data at all.
I've logged query built by CDbCriteria and there was some LIKE conditions which uses mysql default field values, so MySQL searches for entries with default values in required fields.
Since I have none entries matching this condidion it returns 0 rows. But the thing is, I don't need these LIKEs. Is there a way to disable it?
Here's the view:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $model->search(),
'filter' => $model,
'columns' => array(
array(
'name' => 'name',
'type' => 'raw',
'value' => 'CHtml::encode($data->name)'
),
array(
'name' => 'email',
'type' => 'raw',
'value' => 'CHtml::link(CHtml::encode($data->email), "mailto:".CHtml::encode($data->email))',
),
),
));
Controller:
public function actionUsers() {
$model = new Users();
$this->renderPartial('users',array(
'model' => $model,
));
}
Function Search of model Users:
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'user ASC',
),
'pagination'=>array(
'pageSize'=>5
),
));
And Logged Query:
SELECT * FROM `users` `t` WHERE (((((email LIKE :ycp0) AND (`group` LIKE :ycp1)) AND (gender LIKE :ycp2)) AND (city LIKE :ycp3)) AND (name LIKE :ycp4)) AND (av_url LIKE :ycp5) ORDER BY `t`.`name` LIMIT 5. Bound with :ycp0='%NotSet%', :ycp1='%3%', :ycp2='%Secret%', :ycp3='%NotSet%', :ycp4='%NotSet%', :ycp5='%noav.jpg%'
I am new to Stackoverflow and don't have sufficient reputation to post a comment, otherwise I would have asked that you share more information on how you configure your CDbCriteria object in your $model->search() function.
But, I suspect that you are using partial matches in the compare method, which can be disabled by passing false in the $partialMatch parameter as follows:
$criteria = new CDbCriteria;
$criteria->compare('email', $someValue, false);
Or, since false is the default value, you can simple write:
$criteria->compare('email', $someValue);
I have this search using joins. The results are correct but yii grid does not show all of the results even if the pagesize selected is greater than number of result.
here's my code :
if($_GET['BaseIar']['description'] !='empty'){
$criteria->with = array('class','classSi',);
$this->description=$_GET['BaseIar']['description'];
$criteria->compare('class.description', $this->description, true);
$criteria->compare('classSi.description', $this->description, true, 'OR');
}
here are the relations:
public function relations() {
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'class' => array(self::HAS_ONE, 'BaseEiEquipItem', 'iar_no'),
'classSi' => array(self::HAS_ONE, 'BaseSiReceivedItem','iar_no'),
);
}
here's the grid:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'base-iar-grid',
'dataProvider'=>$searchModel->search(),
'columns'=>array(
array(
'class'=>'CCheckBoxColumn',
'id'=>'base-iar-id',
'selectableRows'=>2, // multiple rows can be selected
),
'iar_id',
'dateInspected',
array(
'name'=>'inspectedBy',
'value'=>'(!empty($data->inspectedBy))?$data->inspectedBy0->person->lastName.", ".$data->inspectedBy0->person->firstName." ".$data->inspectedBy0->person->middleName:"---"',
),
array(
'name'=>'endUser',
'value'=>'(!empty($data->endUser))?$data->endUser0->person->lastName.", ".$data->endUser0->person->firstName." ".$data->endUser0->person->middleName:"---"',
),
'dateReceived',
array(
'name'=>'receivedBy',
'value'=>'(!empty($data->receivedBy))?$data->receivedBy0->person->lastName.", ".$data->receivedBy0->person->firstName." ".$data->receivedBy0->person->middleName:"---"',
),
array(
'name'=>'requisitionOffice',
'value'=>'(!empty($data->requisitionOffice))?$data->requisitionOffice0->code:"---"',
'value'=>'$data->requisitionOffice0->code'
),
'prNo',
'poNo',
array(
'class'=>'InfosysButtonColumn',
'template'=>'{view}',
'afterDelete'=>'function(link,success,data){
if(success){
jSuccess("Delete completed successfully!");
}
}',
'buttons'=>array(
'view' => array(
'label' => 'View details',
'url' => 'Yii::app()->createUrl("pims/IAR/BaseIar/view", array("id"=>$data["id"]))'
),
),
'header'=>CHtml::activeDropDownList($model,'pageSize',array('10'=>'10','20'=>'20','30'=>'30','50'=>'50','100'=>'100','ALL'=>'All'),array('onchange'=>'$.fn.yiiGridView.update("base-iar-grid", {data:{pageSize:$(this).val()}});')),
),
)
));
What might be the correct way to declare multiple relations in $criteria->with?
Hey I found this piece of example code in the docs for with(), maybe it'll help you:
Post::model()->with(array(
'author'=>array('select'=>'id, name'),
'comments'=>array('condition'=>'approved=1', 'order'=>'create_time'),
))->findAll();
This question already has an answer here:
Yii Set Default Sort Order in Model
(1 answer)
Closed 9 years ago.
My Yii CGridView Sorting is not working this way when
public function search() {
$criteria = new CDbCriteria;
$criteria->order = "member_id DESC";
When I click header menu in CGridView it is not working but when I remove
$criteria->order = "member_id DESC";`
sorting is working fine. I want to show records by default order by member_id desc.
Remove this line $criteria->order = "member_id DESC";
Amend your return:
return new CActiveDataProvider($this, array(
'criteria' => $criteria,
'sort' => array(
'defaultOrder' => 'member_id DESC',
),
));
Use CActiveDataProvider: In this class CActiveDataProvider you can find the property defaultOrder to set the defult visible order in your grid view with respect to your database table column name.
defaultOrder: defaultOrder is a property in CActiveDataProvider class. This property is belongs to the class CSort. As the class CActiveDataProvider inherited CSort, defaultOrder property became a property of CActiveDataProvider.
The syntax to do your task is
$dataProvider = new CActiveDataProvider('YourModel',
array(
'sort' => array('defaultOrder' => 'member_id DESC')
));
Pass this $dataProvider to your view
$this->render('YourView', array(
'dataProvider' => $dataProvider
));
As you want to presenting the results in CGridView
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'data-grid',
'dataProvider' => $model->search(),
'columns' => array(
'column1',
'column2',
'column3',
array('class' => 'CButtonColumn'),
),
));
I think problem is here
$criteria->order = "member_id DESC";
Just Remove this line and then add in
return new CActiveDataProvider($this,array(
'criteria'=>$criteria,
'sort'=>array(
'defaultOrder'=>'member_id DESC',
),
));
hope it will be help you.
I have a problem that I have solved for all but one of the cgridview filters, which is a related field.
I am using a solution Seenivasan has supplied but the related field status does not get added to the string.
here is the cgridview :-
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'tbl-orders-grid',
'dataProvider'=>$dataProvider,
'afterAjaxUpdate'=>"function() {
jQuery('#Orders_date_first').datepicker(jQuery.extend({showMonthAfterYear:false}, jQuery.datepicker.regional['id'], {'showAnim':'fold','dateFormat':'yy-mm-dd','changeMonth':'true','changeYear':'true','constrainInput':'false'}));
jQuery('#Orders_date_last').datepicker(jQuery.extend({showMonthAfterYear:false}, jQuery.datepicker.regional['id'], {'showAnim':'fold','dateFormat':'yy-mm-dd','changeMonth':'true','changeYear':'true','constrainInput':'false'}));
}",
'filter'=>$model,
'columns'=>array(
array(
'name'=>'id',
'type'=>'raw',
'value'=>'str_pad($data->id,8-strlen($data->id),"0",STR_PAD_LEFT)',
'htmlOptions'=>array('style' => 'text-align: right;width: 60px;')
),
array(
'name'=>'date_order_placed',
'filter'=>$dateisOn,
'value'=>'date("d-m-Y",strtotime($data->date_order_placed))',
),
array(
'name'=>'status',
'type'=>'raw',
//'htmlOptions'=>array('id' => 'order_status_search'),
'value'=>'CHtml::value($data,"status.orders_status_name")',
'filter'=>CHtml::listData(OrderStatus::model()->findAll(
array(
'select'=>array('orders_status_name'),
'distinct'=>true
)),"orders_status_name","orders_status_name")//this is the focus of your code
),
array(
'class'=>'EButtonColumnWithClearFilters',
'clearVisible'=>true,
'template'=>'{view}{email}',
'buttons'=>array
(
'email' => array
(
'label'=>'Reprint invoice and email to yourself',
'imageUrl'=>Yii::app()->request->baseUrl.'/images/email.png',
'url'=>'Yii::app()->createUrl("orders/ureprint", array("id"=>$data->id))',
),
),
),
),
)); ?>
here is the php and js that adds the current filter values to the url.
echo CHtml::button('List Orders',array('id'=>'listelement'));
Yii::app()->clientScript->registerSCript('test','
$("body").on("click","#listelement",function(){
var str="&";
$.each($("#tbl-orders-grid input").serializeArray(),function(i,j){
str=str+j.name+"="+j.value+"&";
});
window.location="'.CHtml::normalizeUrl(array('orders/index')).'"+str;
});
');
The other filters, dates and id, work perfectly. They are added to the url above. Status is not.
1- you need to define new filters in your model serach() methode for example like
$criteria->compare('Restaurant.Name',$this->Name,true);
Restaurant is your relation key , name : value from another table related to this fk
2- you have to add value of gridview column like :
view:
array(
'name' => 'Restaurant.Name',
'header' => 'Username',
'filter' => CHtml::activeTextField($model, 'name'),
'value' => '$data->Restaurant->Name',
This link will help you
yii CGridView filter with relations