Difference between #5 and #6 of
Limit a CGridView field to some preset length.

Revision #6 has been created by le_top on Apr 15, 2013, 11:58:03 AM with the memo:

Added method to set the length of the field.
« previous (#5)

Changes

Title unchanged

Limit a CGridView field to some preset length.

Category unchanged

How-tos

Yii version unchanged

Tags unchanged

CGridView, width, column, tooltip

Content changed

[...]
'type'=>'shortText'),
),
```


That's it. As you can imagine it is pretty easy to add other similar formatters.

 
 
Well, too bad that we can not set some parameters for the format from within the gridview setup, isn't it?  Ok, I have a solution for it.
 
 
First we add an extra method to our implementation of the formatter which overrides the default one, we also update our shortText formatter, and we change our gridview setup.
 
 
 
 
 
```php 
class YFormatter extends CFormatter {
 
    [...]
 
    /**
 
     * Override the default format function to allow paramters to the formatter.
 
     *
 
     * (non-PHPdoc)
 
     * @see CFormatter::format()
 
     */
 
    public function format($value,$type)
 
    {
 
        $params=null;
 
        if(is_array($type)) {
 
            $params=$type;
 
            $type=$type['type'];
 
        }
 
        $method='format'.$type;
 
        if(method_exists($this,$method)) {
 
            if($params===null) {
 
                return $this->$method($value);
 
            } else {
 
                return $this->$method($value,$params);
 
            }
 
        } else {
 
            throw new CException(Yii::t('yii','Unknown type "{type}".',array('{type}'=>$type)));
 
        }
 
    }
 
 
    /** Added '$params' */
 
    public function formatShortText($value,$params=array()) {
 
        if(isset($params['length'])) {
 
            $len=$params['length'];
 
        } else {
 
            $len=$this->shortTextLimit;
 
        }
 
        if(strlen($value)>$len) {
 
            $retval=CHtml::tag('span',array('title'=>$value),CHtml::encode(mb_substr($value,0,$len-3,Yii::app()->charset).'...'));
 
        } else {
 
            $retval=CHtml::encode($value);
 
        }
 
        return $retval;
 
    }
 
```
 
 
 
And a slightly modified way to define this type in our column:
 
 
```php 
'columns'=>array(
 
array('name'=>'description',
 
      'type'=>array('type'=>'shortText','length'=>30,),
 
        ),
 
```
 
 
So now we can set the length of our field.  You can do use the same method for setting paramters for a datetime formatter, ... .
9 0
10 followers
Viewed: 14 605 times
Version: 1.1
Category: How-tos
Written by: le_top
Last updated by: le_top
Created on: Feb 25, 2013
Last updated: 5 years ago
Update Article

Revisions

View all history