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();
Related
I am using grid view with check boxes in yii 1.1, but when I am trying to get checked values, they are returning array of empty values.
-- I have referred all the answers here
-- I have used $.fn.yiiGridView.getChecked("grid-id","selectedIds"); too
Still It's not working for me.
My grid view code is:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'patient-wallet-credit-grid-id',
'dataProvider'=>$dataProvider,
'selectableRows'=>100,
'emptyText'=>"You don't have patients connected yet",
'beforeAjaxUpdate'=>'function(id,options){options.data={checkedIds:$.fn.yiiGridView.getChecked("patient-wallet-credit-grid-id","selectedIds").toString(),
uncheckedIds:getUncheckeds()};
return true;}',
'afterAjaxUpdate'=>'function(){
$("#patient-wallet-credit-grid table").attr("data-tablesaw-mode","columntoggle");
$("#patient-wallet-credit-grid table").attr("data-tablesaw-minimap","");
$("#patient-wallet-credit-grid table").attr("data-tablesaw-sortable","");
$("#patient-wallet-credit-grid table").attr("data-tablesaw-mode-switch","");
$(document).trigger( "enhance.tablesaw" );
}',
'itemsCssClass' =>'tablesaw tablesaw-columntoggle items',
'columns'=>array(
array(
'name' => 'check',
'id' => 'selectedIds',
'value' => '$data["patient_id"]',
'class' => 'CCheckBoxColumn',
'checked'=>'Yii::app()->user->getState($data["patient_id"])',
'headerHtmlOptions'=>array(
'data-tablesaw-priority'=>'1',
'data-tablesaw-sortable-col'=>'',
'class'=>'',
'style'=>"width:10px"
)
),
array(
'name'=>'Name',
'value'=>'$data["patient_first_name"]',
'headerHtmlOptions'=>array(
'data-tablesaw-priority'=>'1',
'data-tablesaw-sortable-col'=>'',
'class'=>'start-xs'
),
),
array(
'name'=>'Mobile',
'value'=>'$data["patient_id"]',
'headerHtmlOptions'=>array(
'data-tablesaw-priority'=>'1',
'data-tablesaw-sortable-col'=>'',
'class'=>'start-xs'
),
),
),
'htmlOptions'=>array(
'style'=>'overflow: auto;'
),
));
I have written the function getUnchecked() in same view ---
Yii::app()->clientScript->registerScript('getUnchecked', "
function getUncheckeds(){
var unch = [];
/*corrected typo: $('[name^=someChec]') => $('[name^=someChecks]') */
$('[name^=someChecks]').not(':checked,[name$=all]').each(function(){unch.push($(this).val());});
return unch.toString();
}
"
);
When I am trying to get values in console by
$.fn.yiiGridView.getChecked("patient-wallet-credit-grid-id","selectedIds");
Suppose I am selecting 3 check boxes Then I get Output like ----
(3) ["", "", ""]
0: ""
1: ""
2: ""
length: 3
__proto__: Array(0)
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..
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.
How can I create a search form/criteria for "one-to many" relations: let's say "select all teams with crowd > 10.000".
I'm using MongoRecord extension (http://www.yiiframework.com/extension/mongorecord/) as a basic active record for MongoDb.
I created a GridView with Yii based on a collection from a mongo db (it works for me).
One of my document`s collection has a structure like this:
{
_id":1,
"teamId":2453,
"teamName":"Team A",
"competition":["Competition A","Competition B"],
"matches":
[
{
"_id":147852,
"crowd":10234,
"yellowCards":2,
"scorers" [{....}]
....
}
]
...
}
My documents:
$teams = MongoTeam::model()->findAll();
My dataProvider is:
$dataProvider=new CArrayDataProvider($teams, array(
'id'=>'_id',
'sort'=>array(
'attributes'=>array(
'_id', 'teamId', 'teamName', 'matches', ...
),
),
'pagination'=>array(
'pageSize'=>20,
),
));
$this->render('index', array('dataProvider'=>$dataProvider));
And in the view I have something like this:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
array(
'name' => 'Team ID',
'type' => 'raw',
'value' => 'CHtml::encode($data->teamID)'
),
array(
'name' => 'Team Name',
'type' => 'raw',
'value' => 'CHtml::encode($data->teamName)'
),
...
But I'm not able to create filters with criteria for subdocuments (my case: "matches"). I don't want to use any other mongoDB extension/module etc.
Thanks and sorry for my bad english.
$query=array(
'matches.crowd'=>array('$gt'=>10000),
'matches.$'=>1
);
$teams = MongoTeam::model()->findAll($query);
You can use like this. But you must not use a data provider like that. Because it will generate too much rows into the $teams var. You must use criteria for data providers. I am doing that with YiiMongoDbSuite it has EMongoCriteria and EMongoDataProvider classes to accomplish that.
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