不允许删除方法 (#405) gridview yii2

Delete is not working Method Not Allowed (#405) gridview yii2

这是我的 gridview,我从 class actionColumn 改为:

[   'format' => 'html',
            'contentOptions'=>['style'=>'width: 5px;'],
            'value' => function($model) {
                if($model->id == Yii::$app->user->identity->id) {
                    return  Html::a('<i class="glyphicon glyphicon-share-alt"></i>').' '. 
                            Html::a('<i class="glyphicon glyphicon-pencil"></i>', ['update', 'id' => $model->id]).' '.
                            Html::a('<i class="glyphicon glyphicon-trash"></i>', ['delete', 'id' => $model->id], ['data' => ['confirm' => 'Do you really want to delete this element?','method' => 'post']]);
                }
                return '';
            },
        ],

这给我一个错误。

Method Not Allowed (#405)

Method Not Allowed. This url can only handle the following request methods: POST. 

当我再次更改为 actionColumn 时,它可以正常工作,但我更改了代码,它只是给我一个错误。

由于 html 格式化程序将 清理 使用 HtmlPurifier 的值,您只需将格式更改为 raw .

阅读更多:http://www.yiiframework.com/doc-2.0/guide-output-formatter.html#other-formatters

你还可以做的是在 actioncolumn 中设置按钮参数见 http://www.yiiframework.com/doc-2.0/yii-grid-actioncolumn.html#$buttons-detail

例如像这样:

      'buttons' => [
            'update' => function ($url, $model, $key) {
                if ($model->id == Yii::$app->user->identity->id) {
                    $options = [
                    'title' => Yii::t('yii', 'Update'),
                    'aria-label' => Yii::t('yii', 'Update'),
                    'data-pjax' => '0',
                    ];
                    return Html::a('<span class="glyphicon glyphicon-pencil"></span>', $url, $options);
                }
            },
            'delete' => function ($url, $model, $key) {
                if ($model->id == 6929) {
                    $options = [
                    'title' => Yii::t('yii', 'Delete'),
                    'aria-label' => Yii::t('yii', 'Delete'),
                    'data-confirm' => Yii::t('yii', 'Are you sure you want to delete this item?'),
                    'data-method' => 'post',
                    'data-pjax' => '0',
                    ];
                    return Html::a('<span class="glyphicon glyphicon-trash"></span>', $url, $options);
                }
            },
        ],

但我只想从 ActionColumn Class 扩展我自己的 class 创建一个这样的函数。我了解您的代码,所有按钮都应隐藏或显示,具体取决于模型->id 是用户->identity->id

protected function renderDataCellContent($model, $key, $index)
{
    if ($model->id == Yii::$app->user->identity->id) {
        return parent::renderDataCellContent($model, $key, $index);
    }
}

希望这对您有所帮助。 我会使用带有扩展 Actioncolumn class 的方法。因为那时所有链接仍然有效,例如更改 urlCreator 函数或为网格启用 pjax 等

尽管如此,post 请求无效的原因是正确的,正如 soju 上面所写的那样。