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.
Related
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..
One field in CGridView is a 'quota' field with a value in bytes. To make it human-readable, I'm using CFormatter:
'columns' => array(
...
array(
'name' => 'quota',
'value' => function($data) {
return Yii::app()->format->formatSize($data->quota);
},
),
),
Now I'd like to filter data in this column by megabytes. I've modified the search() method in model like this:
$criteria->compare('(quota / 1024 / 1024)',$this->quota,true);
but I don't like how it looks like. Is there a normal workaround?
Thank you.
Instead of
array(
'name' => 'quota',
'value' => function($data) {
return Yii::app()->format->formatSize($data->quota);
},
),
You could simply do:
'quota:size',
Now, to answer your question, using the compare function is wrong, as it adds a "WHERE" clause to the SQL query. You are looking to do a sort instead using the order property:
$criteria = new CDbCriteria;
$criteria->order = "quota DESC";
EDIT (after your comment):
$criteria = new CDbCriteria;
$criteria->addCondition('quota > '.intval($this->quota)*1024*1024);
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);
Suppose I have model User which have many to many relation to itself named as friends.
so $user->friends (or $model->friends in view) gives me an array of User objects. I wanted to display the friends as gridview. But CGridView data as dataProvider object. Googling for it found the way to convert array of model objects to dataProvider object as given below.
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' => new CArrayDataProvider($model->friends, array()),
));
Now using this I get an error
Property "User.id" is not defined.
UPDATE
public function relations()
{
return array(
'friends' => array(self::MANY_MANY, 'User', 'friendship(user_id, friend_id)'),
);
}
I use two stage building the provider shown below. But I found that it gives you trouble in terms of Pagination. I have not bothered to resolve that problem since am doing other things
$dataProvider = new CArrayDataProvider('User');
$dataProvider->setData($model->friends);
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' =>$dataProvider,
));
That being said, your code should work (see the example below from API docs). I suspect there is wrong attribute in your relations than the provided code. Re-check the relation definition if it is ok
From Yii docs:
$rawData=Yii::app()->db->createCommand('SELECT * FROM tbl_user')->queryAll();
// or using: $rawData=User::model()->findAll(); <--this better represents your question
$dataProvider=new CArrayDataProvider($rawData, array(
'id'=>'user',
'sort'=>array(
'attributes'=>array(
'id', 'username', 'email',
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
Got it :) , i can use CActiveDataProvider instead of CArrayDataProvider as given below
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'gridUser',
'dataProvider' => new CActiveDataProvider('User', array(
'data'=>$model->friends,
)),
//...... columns display list.....
));
Anyways thanks for the reply #Stefano