How to sort the fields from relation table in Yii? - yii-extensions

I am trying to implement sorting with Yii list view. I have joined 2 tables named provider_favourite and service_request in list view. And the fields and contents from both tables are listing in the list view. But sorting is working only in provider_favourite table, not from service_request table.How can I sort the fields from service_request table? Iam using csort for sorting. I also tried CGrid view. But the same problem is happening in grid view also ..
Iam using the following code to join
$criteria = new CDbCriteria;
$criteria->select = 'favourite_notes,favourite, favourite_added_date,max_budget,preferred_location,service_name';
$criteria->join = 'LEFT JOIN service_request AS s ON service_request_id = favourite';
$criteria->condition = 'favourite_type = 1';
$sort=new CSort('ProviderFavourite');
// $sort->defaultOrder='s.max_budget ';
$sort->applyOrder($criteria);
$sort->attributes = array(
'max_budget' => 'service_request.max_budget',
'service_name' => 'service_request.service_name',
'favourite_added_date'
);
$type = 2;
$data = new CActiveDataProvider('ProviderFavourite', array('criteria' => $criteria, 'pagination' => array('pageSize' => 4),'sort'=>$sort
));
$this->renderPartial('favourites', array(
'ModelInstance' => ProviderFavourite::model()->findAll($criteria),
'dataProvider' => $data, 'type' => $type, 'sort'=>$sort,
));
and also Iam providing sortable attributes in list view
$this->widget('zii.widgets.CListView', array('dataProvider'=>$dataProvider,'itemView'=>'index_1',
'id'=>'request',
'template' => ' {items}{pager}',
'sortableAttributes'=>array('favourite_notes','max_budget','service_name')
));
If more details needed, I will provide. Thanks in advance

You have to specify attributes property of your $sort instance. By default only fields of $modelClass (ProviderFavourite in your case) are sortable.
I think it could look like this (not tested):
$sort->attributes = array(
'service_name' => array(
'asc' => 's.service_name ASC',
'desc' => 's.service_name DESC'
),
// ...another sortable virtual attributes from service_request table
"*"
);

You should not create a CSort object in $sort. The CActiveDataProvider will already provide you with the right sort object. The way you do it, you apply the sort criteria to $criteria before you configure the sort attributes. That can not work.
You should try a simple setup like this instead:
$data = new CActiveDataProvider('ProviderFavourite', array(
'criteria' => $criteria,
'pagination' => array('pageSize' => 4),
'sort'=> array(
'attributes' => array(
'service_name' => array(
'asc' => 's.service_name ASC',
'desc' => 's.service_name DESC'
),
// ...
),
));
If you need to access the related CSort object (which you usually don't if you use a CGridView or CListView, because they deal with that for you), then you get it via $data->sort.

Related

Sorting in yii 1.1

I have question regarding yii 1.1 sort.
I have three tables ticket, repairLogs and part table .
Following relations have been defined in Ticket model.
'repairLogs' => array(self::HAS_MANY, 'RepairLog', 'ticket_id', 'order'=>'ts DESC'),
and in repairLogs Table
'part' => array(self::BELONGS_TO, 'Part', 'part_id'),
Part table has a column 'number' and I want to sort the data based on "number". Can anyone guide me how to do this since I am new to the yii 1.1 framework.
You can do this during the find()
Ticket::model()->with(array('part', 'repairLogs'))->findAll(
array(
// your conditions here
'order' => 'part.number DESC', // "part" is the alias defined in your relation array (in the Ticket model file)
'limit' => 10,
)
);
If you are using A dataProvider, you can set it as a default order:
new CActiveDataProvider('Ticket', array(
'criteria' => $criteria, // you criteria that should include the "with" part
'sort' => array(
'defaultOrder' => 'part.number DESC',
)
));

Displaying value from join table in Yii CgridView

I have this very simple table in my view and I'm trying to display value from joined table:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'skills-grid',
'dataProvider'=>$model->searchWithStudentSuccessRate($id),
'template' => '{items}{pager}',
'cssFile'=>Yii::app()->request->baseUrl. '/themes/'. Yii::app()->theme->name.'/css/table.css',
'htmlOptions'=>array('class'=>'datagrid', 'style'=>'width:550px;'),
'columns'=>array(
array(
'name'=>'name',
),
array(
'name' => 'value',
'header' => Yii::t('MainTrans', 'Value'),
'value' => '$data->student_skills->value',
),
array(
'name' => 'successRate',
'header' => Yii::t('MainTrans', 'Success Rate'),
'value' => '$data->successRate."%"',
),
),
));
And this is the search function:
public function searchWithStudentSuccessRate($id)
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('id',$this->id);
$criteria->compare('name',$this->name,true);
$criteria->compare('t.threshold',$this->threshold);
$criteria->with = array('student_skills');
$criteria->together = true;
$criteria->select = array('IFNULL(CASE WHEN ROUND((student_skills.value/t.threshold)*100,0) > 100 THEN 100 ELSE ROUND((student_skills.value/t.threshold)*100,0) END,0) as successRate','*');
$criteria->group = "t.name";
$criteria->condition = 'student_skills.student_id = '.$id;
$criteria->compare('successRate',$this->successRate);
$criteria->compare('student_skills.value',$this->value);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
'pagination'=>array(
'pageSize'=>25,
),
'sort'=>array(
'defaultOrder'=>array(
'successRate'=>CSort::SORT_DESC,
),
'attributes'=>array(
'successRate'=>array(
'asc'=>'successRate',
'desc'=>'successRate DESC',
),
'*',
),
),
));
}
But I get error: "Trying to get property of non-object" when I added value column to my CGridView.
Everything works fine without column value (columns successRate and name are fine). Relation should be fine as well. The error I get means that the value doesn't exist but it should since I did something similar in my other views and there it works.
Can anyone tell what's wrong? I'm sure it's something minor but I'm struggling with this embarrasing problem for a while.
Thanks
It means that in some conditions $data->student_skills is NULL. Try change this:
'value' => '$data->student_skills->value',
to this
'value' => 'empty($data->student_skills) ? null : $data->student_skills->value',

Customised query to display in CGridView in yii

Controller,
$model=Product::model()->display_products_statistics();
$this->render('admin',array(
'model'=>$model,
));
View,
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'product-grid',
'dataProvider' => $model->display_products_statistics(),
'filter'=> $model,
'columns'=> array(
'member_count',
'seller_count',
'visitor_count',
'lowest price',
'desc',
'price',
'createdate',
'updatedate',
'opid',
'pimg',
array(
'class'=>'CButtonColumn',
),
),
));
Model,
$sql="select member_count,seller_count,
visitor_count from fc_product fp
group by member_count,visitor_count,seller_count
order by member_count desc";
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$products_statistics=$command->queryAll();
$dataprovider=new CArrayDataProvider($products_statistics,
array('pagination'=>false));
return $dataprovider->getData();
But then I am getting this error
Fatal error: Call to a member function getData() on a non-object in D:\wamp\www\yii\framework\zii\widgets\CBaseListView.php on line 111
I am confused and don't know what's going wrong.
Your problem is that you are not using CDataProvider in the correct way. CGridView needs an instance of CDataProvider to display, but you have used CDataProvider->getData() instead. I'd also recommend using CSqlDataProvider, which is purpose made for custom sql queries. Try this in your model;
$count = Yii::app()->db->createCommand('SELECT COUNT(*) FROM fc_product')->queryScalar();
$sql="select member_count,seller_count,
visitor_count from fc_product fp
group by member_count,visitor_count,seller_count
order by member_count desc";
return new CSqlDataProvider($sql, array(
'totalItemCount' => $count,
'sort' => array(
'attributes' => array(
'member_count', 'visitor_count', 'seller_count',
),
),
'pagination' => false

yii CGridView dataprovider and filter

I know we can show a gridview with a model and it's search method and filter the results, but can we make a gridview with another dataprovider and another model like this and filter its results? Does filter needs to be a part of dataprovider?
$attr = Yii::app()->request->getParam($name);
$model = new User('search');
$model->unsetAttributes();
$model->setAttributes($attr);
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => $myDataProvider,
'filter' => $model,
'columns' => array(
array(
'name' => 'username',
'type' => 'raw',
'value' => 'CHtml::encode($data->username)'
),
array(
'name' => 'email',
'type' => 'raw',
),
),
));
The above code doesn't work and I need to add a filter on a previously made data provider.
Btw $attr has a valid data, but grid is not filtered.
$model doesn't affect $myDataProvider since the data provider is not obtained using this model.
$model->search() returns a CActiveDataProvider which contains a CDbCriteria instance. Different CDbCriteria can be combined using mergeWith(). So if you would like the data to be filtered using the values from the $model
...
$model->setAttributes($attr);
$newDataProvider=$model->search();
$myDataProvider->criteria->mergeWith($newDataProvider->criteria);
$this->widget('zii.widgets.grid.CGridView', array(
...
Filter does not need to be a part of dataprovider, but data provider needs to take the model into account, if you want to use it for filtering.
The way this is done by default is to create the data provider using search method on your model, which sets conditions of your data provider based on model values, like so:
'dataProvider' => $model->search()
There is nothing preventing you from creating different data provider, for example:
'dataProvider' => $model->createAnotherDataProvider()
And in your User model:
public function createAnotherDataProvider() {
{
// create your second data provider here
// with filtering based on model's attributes, e.g.:
$criteria = new CDbCriteria;
$criteria->compare('someAttribute', $this->someAttribute);
return new CActiveDataProvider('User', array(
'criteria' => $criteria,
));
}

like OR operator in Cakephp

I am new to cakephp and I want to add or, and, and like to my existing query.
I want to make a condition like this
WHERE 'Message.user_id = Contact.user_id' AND 'Message.mobileNo LIKE'=>"%Contact.mobileNo" OR LIKE'=>"%Contact.homeNo" OR LIKE'=>"%Contact.workNo"
My query is
$this->bindModel(array(
'belongsTo' => array(
'Contact' => array(
'className' => 'Contact',
'foreignKey' => false,
'conditions' => array(
'Message.user_id = Contact.user_id',
'Message.mobileNo = Contact.mobileNo'
),
'type' => 'inner'
)
)
), false);
$this->find('all', array('conditions' => array(),
'fields' => array('DISTINCT mobileNo')));
you can use like below in your existing query.
$this->find('all', array(
'conditions' => array(
'OR' => array(
array(
"Message.mobileNo LIKE" => "%Contact.mobileNo",
),
array(
"Message.mobileNo LIKE" => "%Contact.homeNo",
),
array(
"Message.mobileNo LIKE" => "%Contact.workNo",
)
)
),
'fields' => array('DISTINCT mobileNo')
));
And you can also refer Detail Document for simple search with like
you can use: for "like"
$this->Post->find("all",array('condition'=>array('Author
LIKE'=>"ad%")));
above query will give You the data from table posts where author name starts with "ad".
for "OR"
$this->Post->find("all",array('condition'=>array("OR"=>array('Author
LIKE'=>"ad%",'Author LIKE'=>"bo%"))));
above query will give You the data from table posts where author name starts with "ad" OR "bo"
This blog post can b useful to u as well!