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

unchanged
Title
Limit a CGridView field to some preset length.
unchanged
Category
How-tos
unchanged
Tags
CGridView, width, column, tooltip
changed
Content
Sometimes text inside a gridview column is just too long.  That's why I figured
out a way to make the column smaller while still providing the information.

How about the example just below.  Hover over the text to see what happens:

<b><span title="Create test account for Yii.  This is quite
long.">Create test acco...</span></b>

Right: the full text appears when you hover over the text.

That's great for the backoffice grid views where you often show tons of
information.
If you want fancier effects, you can achieve them using bootstrap tooltips for
instance in a similar way.  The purpose of this article is to present a method
to do this (which in itself already works!).

The method consists of:
1) Creating a new formatter method.
2) Refer to the formatter method in the CGridView column specification.

1) a) Create the formatter method:
~~~
[php]
class YFormatter extends CFormatter {
    /* @var int The text length limit for the ShortText formatter. */
    public $shortTextLimit= 20;
    /**
     *
     * Text formatter shortening long texts and displaying the full text
     * as the span title.
     *
     * To be used in GridViews for instance.
     * @param string $value
     * @return string  Encoded and possibly html formatted string ('span' if the
text is long).
     */
    public function formatShortText($value) {
        $retval=CHtml::encode($value);
        if(strlen($value)>$this->shortTextLimit) {
           
$retval=CHtml::tag('span',array('title'=>$value),CHtml::encode(mb_substr($value,0,$this->shortTextLimit-3,Yii::app()->charset).'...'));
        } else {
           
$retval=CHtml::encode($value);$retval=CHtml::tag('span',array('title'=>$retval),CHtml::encode(substr($value,0,$this->shortTextLimit-3).'...'));
        }
        return $retval;
    }
}
~~~

1) b) Make sure that your formatter class is used by adjusting the project
configuration:
Specify the new formatter as class for the 'format' component in config.php:

~~~
[php]
   'components'=>array(
        'format'=>array(
            'class'=>'YFormatter',
        ),
    ),
~~~



2) In the gridview, specify 'shortText' as the formatter (because we called our
formatter method 'formatShortText'):


~~~
[php]
    'columns'=>array(
	array('name'=>'description',
		  'type'=>'shortText'),
),
~~~


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