Limit Length of Column Value in Yii Bootstrap TbGridView

October 16th, 2013 - Posted by Steve Marks to Javascript / jQuery, PHP, Web Development.

I’ve recently been working on a project built on the Yii framework that uses Yii-Bootstrap to make working with Yii and Bootstrap together a little easier.

One of the widgets I frequently used was the TbGridView; A widget that outputs a table. Getting it integrated was easy enough but a particular scenario came up that I couldn’t find described anywhere online.

One of the columns in the table was a freeflow textfield with no set limit. I wanted to display this field in the grid but displaying the whole thing would mess up the layout:

What I wanted to do was limit the length of the text displayed and only display the first few characters. After all, the only reason I was displaying it in the grid was to highlight which records had this text entered, and which ones didn’t.

The solution was simple enough and involved modifying the column’s value when loading the widget. This code can be seen below:

$this->widget('bootstrap.widgets.TbGridView', array(
    'id' => 'my-grid',
    'dataProvider' => $model->search(),
    'filter' => $model,
    'columns' => array(
            'header' => 'Description',
            'name' => 'description',
            'value' => '(substr($data->description, 0, 30) . ( (strlen($data->advice_letter_text) > 30) ? \'...\' : \'\' ) ) '

As you can see, our ‘Description’ column has had the value specifically set and is using the substr() function to limit it to just 30 characters. I’m then adding a ‘…’ at the end if the description exceeds this length.

It now looked like so:

My only concern regarding doing this was that the search filter would then stop working. Fortunately, even though we’d trimmed the text, the filter still searched the whole text and returned the correct results.

Tags: , ,
This entry was posted on Wednesday, October 16th, 2013 at 10:10 am by +Steve Marks and is filed under Javascript / jQuery, PHP, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.

Fear not, we won't publish this

Comments (1)
  1. Alino says:

    thank your for this,
    I found this helpful