Tuesday, April 30, 2013

CGridView a CLinkColumn with sortable header using yii

I have it working with the latest yii (non-stable but might work with the current stable release). (could do with some improvement but it does what I need)

Try this; create a new component under components/SCLinkColumnWithSort.php

<?php
class SCLinkColumnWithSort extends CLinkColumn
{

  public $name;
  public $sortable = true;
  public $filter;

  protected function renderFilterCellContent()
  {
    $this->linkHtmlOptions['class'] = $this->name;
    if($this->filter!==false && $this->grid->filter!==null && strpos($this->name,'.')===false)
    {
      if(is_array($this->filter))
        echo CHtml::activeDropDownList($this->grid->filter, $this->name, $this->filter, array('id'=>false,'prompt'=>''));
      else if($this->filter===null)
        echo CHtml::activeTextField($this->grid->filter, $this->name, array('id'=>false));
      else
        echo $this->filter;
    }
    else
      parent::renderFilterCellContent();
  }

  protected function renderHeaderCellContent()
  {
    if($this->grid->enableSorting && $this->sortable && $this->name!==null)
      echo $this->grid->dataProvider->getSort()->link($this->name,$this->header);
    else
      parent::renderHeaderCellContent();
  }

}
?> 
Use this as following: 

<?php
$this->widget('zii.widgets.grid.CGridView', array(
  'dataProvider' => $dataProvider,
  'columns' => array(
    array(
      'class' => 'SCLinkColumnWithSort',
      'name' => 'column_name_to_sort',
     )
  )
))
?> 
 
Or you can directly use, but upper one used for more customization:
array(
  'name' => 'mobile_number',
  'type' => 'raw',
  'value' => 'CHtml::link($data->mobile_number,$data->contact_id)'
) 
Where mobile_number is filed value in name, in value, mobile_number is for sorting
and contact_id is for making link.

No comments:

Post a Comment