Gibs
Gibs

Reputation: 774

Proper way of redirecting to an action when a row is clicked (onclick) Yii2

I am new to Yii2 so pardon me if this is a simple question. Under this url http://localhost/index.php/host it displays the index. Also, when the url is like this http://localhost/index.php/host/index it displays the same thing.

The problem comes up when I click a row in the Gridview. Here's my index.php under my view.

<?= 
        GridView::widget([
            'dataProvider' => $dataProvider,
            'filterModel' => $searchModel,
            'columns' => [
                'id',
                'name',
                'hostgroup_id',
                'ip_address' => [
                    'label' => 'IP',
                    'attribute' => 'ip_address'
                ],
                'private_address' => [
                    'label' => 'Private IP',
                    'attribute' => 'private_address'
                ],
                'object_name',
                ['class' => 'yii\grid\ActionColumn',
                    'template' => '{delete}',
                ],
            ],

            'rowOptions' => function($model, $key, $index, $grid) {

                $var = Yii::$app;
                return [
                    'id' => $model['id'],
                    'onclick' => 'window.location.href=\'update/'.'\'+(this.id);',
                ];
            }
    ]); ?>

When I am in the url http://localhost/index.php/host/index and I click a link I am redirected to http://cms.dev/index.php/host/update/1

But when I am under http://localhost/index.php/host/ I am redirected to http://cms.dev/index.php/update/1

I think my onclick for my rowOptions value is not right. Any suggestions?

Upvotes: 0

Views: 1579

Answers (2)

Clyff
Clyff

Reputation: 4076

You could also use Url::to() for that:

'rowOptions' => function($model) {
    $url = Url::to(['controller/action', 'id' => $model['id']]);

    return [
        'onclick' => "window.location.href='{$url}'"
    ];
}

If you are using current controller/view than you can use like this example

Eg

$url = Url::to([Yii::$app->controller->id.'/view', 'id' => $model['id']]);

Upvotes: 2

ScaisEdge
ScaisEdge

Reputation: 133360

In not clear because don't set the localhost but you can try using url helpers this way

add the reference to urlHelper on the top

use yii\helpers\Url;

.

   return [
      'id' => $model['id'],
      'onclick' => "window.location.href='" . 
         Url::to(['update' , 'id' => $model['id'])  "'",
   ];

(this is with relative path but if you need you can assigne a absolte path related to teh app.)

Upvotes: 1

Related Questions