单击一行时重定向到动作的正确方法(onclick)Yii2

时间:2015-12-17 13:17:10

标签: javascript php yii2

我是Yii2的新手,请原谅我,如果这是一个简单的问题。在此网址http://localhost/index.php/host下,它会显示索引。此外,当网址如此http://localhost/index.php/host/index时,它会显示相同的内容。

当我点击row中的Gridview时出现问题。在我看来,这是我的index.php。

<?= 
        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);',
                ];
            }
    ]); ?>

当我在网址http://localhost/index.php/host/index中并点击链接时,我被重定向到http://cms.dev/index.php/host/update/1

但当我在http://localhost/index.php/host/之下时,我被重定向到http://cms.dev/index.php/update/1

我认为我的onclickrowOptions不对。有什么建议吗?

2 个答案:

答案 0 :(得分:2)

您也可以使用Url::to()

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

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

如果您使用的是当前控制器/视图,则可以使用此示例

例如

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

答案 1 :(得分:1)

不清楚,因为没有设置localhost,但你可以尝试使用url helpers这样

在顶部添加对urlHelper的引用

use yii\helpers\Url;

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

(这是相对路径,但如果你需要,你可以设置一个与应用程序相关的绝对路径。)