Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate text in a specific Yii2 GridView column and show it on hover?

I render a table using the GridView widget:

<?= GridView::widget([
    'dataProvider' => $dataProvider,
    'filterModel' => $searchModel,   
    'columns' => [
        'subject',
        // ...
    ],
]) ?>

I need to truncate the text displayed in the "subject" column and show it fully on hover, while also preserving the filter row search capability.

I managed to truncate the text using StringHelper::TruncateWords(), but couldn't figure out the filter row and the hover part:

[
            'attribute' => 'subject',
            'value' => function($model) {
                $ret = \yii\helpers\StringHelper::truncateWords($model->subject, 5, '...', false);
                return $ret;
            }
],

Maybe there is a way to do this with pure Bootstrap without the need for StringHelper, but I wasn't able to make it work...

like image 628
Adam Vtípil Avatar asked Oct 24 '25 23:10

Adam Vtípil


1 Answers

There is actually much simpler solution. You can use pure CSS to do this.

.truncate {
   max-width: 150px !important;
   overflow: hidden;
   white-space: nowrap;
   text-overflow: ellipsis;
}

.truncate:hover{
   overflow: visible;
   white-space: normal;
   width: auto;
}

And in view just add the class:

[
  'attribute' => 'subject',
  'contentOptions' => ['class' => 'truncate'],
],

Adjust max-width to your desire, add other effects via css3 and you are done.

like image 111
Nimer Avatar answered Oct 27 '25 00:10

Nimer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!