Yii2使用请求POST删除记录

时间:2018-09-04 23:08:21

标签: yii2-advanced-app

如何使用请求POST从数据库(MySQL)删除记录?

视图中:

<a href="<?= Url::to(['user/delete', 'id' => Html::encode($user->id)]) ?>" class="btn btn-danger">Delete</a>

在控制器中:

public function actionDelete($id)
{
    $model = User::findOne($id);

    if (Yii::$app->request->isPost) {
        $model->delete();
        Yii::$app->session->setFlash('success', 'User deleted successfully');
    }

    return $this->redirect(['user/index']);
}

此代码仅在请求GET时删除。

1 个答案:

答案 0 :(得分:0)

像这样设置删除按钮

<?= Html::a('Delete', ['user/delete', 'id' => $user->id], [
                'class' => 'btn btn-danger',
                'data-confirm' => 'Are you sure?',
                'data-method' => 'post',
            ]) ?>

HTML类是

使用yii \ helpers \ Html;