Jump to content
Larry Ullman's Book Forums

Sort Grid View By Virtual Attribute


Ziggi
 Share

Recommended Posts

Hmm,

 

I must say it is a bit disappointing to see entire "virtual attribute" concept mostly misleading.

 

Well,

 

I have this inside my 'Users' model:

 

public $fullname;

{other code here - not really important}

public function search()
{

 $sort = new CSort();
 $sort->attributes = array('*', 'CONCAT(surname, ", ", forename) AS fullname');
 $sort->defaultOrder = array('fullname' => CSort::SORT_ASC);

$criteria=new CDbCriteria;
 $criteria->select = array('*', 'CONCAT(surname, ", ", forename) AS fullname');
 $criteria->compare('id', $this->id);
$criteria->compare('login', $this->login, true);
 $criteria->compare('surname', $this->surname, true);
 $criteria->compare('forename', $this->forename, true);
 $criteria->compare('email', $this->email, true);
$criteria->compare('CONCAT(surname, ", ", forename)', $this->fullname, true);
$criteria->compare('company_id', $this->company_id);
$criteria->compare('grupa', $this->grupa);
$criteria->compare('active', $this->active);

return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
	 'pagination'=>array('pageSize'=>10),
	 'sort' => $sort,
));
}

 

Having this I have a nice working CGridView and Advanced Search pane but for whatever reason "fullname" column is not sortable.

 

Any idea??? - I feel already exhausted fighting with this all alone...

Link to comment
Share on other sites

Here you are - I made a bug report:

 

https://github.com/y...yii/issues/1899

 

Nevertheless, the workin solution is:

 

return new CActiveDataProvider($this, array(
           'criteria'=>$criteria,
	    'pagination'=>array('pageSize'=>10),
	    'sort' => array(
		    'attributes'=>array(
			    'fullname'=>array(
				    'asc'=>'CONCAT(surname, forename) ASC',
				    'desc'=>'CONCAT(surname, forename) DESC',
			    ),
			    '*',
		    ),
		    'defaultOrder' => 'fullname ASC',
	    ),
       ));

Link to comment
Share on other sites

I would say that's an acceptable "workaround". I haven't read the documentation for this, but if that solution is stated clearly, I find it both pretty and logical. I tend to think example usage of code lacks from the YII documentation, but maybe that's just me.

 

Glad you solved it. If it's possible, you should add a guide on virtual attributes in the manual.

Link to comment
Share on other sites

Yes, this way of construction CSort objects is documented but actually I believe the problem is deeper and missing support for virtual attributes within CActiveRecord->hasAttribute() method may in fact affect virtual attributes usage in a more complex way.

 

Anyway - I have no time to spent on this any more. I am in serious delay already!

Link to comment
Share on other sites

 Share

×
×
  • Create New...