Answer the question
In order to leave comments, you need to log in
How to sort in Yii according to adjacent table data?
There is Yii1. It has 2 models Users(id,name,surename) and Contacts(id,phone,email). Relationship between models 1 to 1.
There is a page with CGridView where data is displayed: Users.id, Users.name, Users.surename, Contacts.phone, Contacts.email.
For the phone and email fields, you need to do filtering and sorting like other fields. I did the filtering, but the trouble with sorting.
Here is the controller:
public function actionAdmin()
{
$model=new Users('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Users']))
$model->attributes=$_GET['Users'];
$this->render('admin',array(
'model'=>$model,
));
}
*/
public function search()
{
// @todo 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('surename',$this->surename,true);
if ($this->phone){
$criteria->with[] = 'contacts';
$criteria->compare('contacts.phone', $this->phone,true);
}
if ($this->email){
$criteria->with[] = 'contacts';
$criteria->compare('contacts.email', $this->email,true);
}
$sort = new CSort;
$sort->attributes= array(
'contacts.email'=>array(
'defaultOrder'=>'contacts.email asc',
'desc'=>'contacts.email DESC'),
'contacts.phone',
'*',
);
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
'sort'=>$sort,
));
}
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'users-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'name',
'surename',
'email'=>array(
'header'=>'Email',
'value'=>'$data->contacts->email',
'filter'=>CHtml::activeTextField($model,'email')
),
'contacts.phone'=>array(
'header'=>'Phone',
'value'=>'$data->contacts->phone',
'filter'=>CHtml::activeTextField($model,'phone')
),
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Answer the question
In order to leave comments, you need to log in
Try this:
1.
remove from under conditions
2. here
'contacts.phone'=>array(
'header'=>'Phone',
'value'=>'$data->contacts->phone',
'filter'=>CHtml::activeTextField($model,'phone')
),
return new CActiveDataProvider(get_class($this), array(
'criteria'=>$criteria,
'sort'=>[
'defaultOrder' => 'contacts.email ASC',
'attributes' => [
'contacts.phone' => [
'asc' => 'contacts.phone ASC',
'desc' => 'contacts.phone DESC'
],
'contacts.email' => [
'asc' => 'contacts.email ASC',
'desc' => 'contacts.email DESC'
],
'*'
]
],
));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question