zuups
zuups

Reputation: 1140

Yii2 gridview: sending attribute value to filter

I want that a text in gridview is link that sends this text to filter of the same column.

so far I'm doing this way:

  'columns'=>[
  ...
  [
    'attribute'=>'colname',
    'value'=>function($data){
       return Html::a($data->colname,Yii::$app->request->url.'&MymodelSearch[colname]='.$data->colname);
     },
  ],
  ...
]

but it's ugly and doesn't always work

Upvotes: 1

Views: 645

Answers (1)

Ripper
Ripper

Reputation: 1162

'columns' => [
// ...
[
    'attribute' => 'colname',
    'format' => 'raw',
    'value' => function ($data, $key, $index, $column) {
        if ($data->colname)
            return 
                "<span onclick=\""
                    . (new \yii\web\JsExpression("setFilterColname('"
                            . Html::encode($data->colname) . "');"))
                . "\">"
                . \yii\helpers\Html::encode($data->colname)
                . "</span>";
    }
// ...
]

Add this at bottom of view file

<?php
$this->registerJs("
    function setFilterColname(filter_value) {
        $('input[name=\"MymodelSearch[colname]\"]').val(filter_value);
        $('#w0').yiiGridView('applyFilter');
        // #w0 is ID of grid to be submited to filter
    } 
", $this::POS_END, 'set-filter-colname');
?>

Upvotes: 1

Related Questions