Yii2删除请求POST的记录

问题描述 投票:0回答:1

如何使用请求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时删除。

yii2-advanced-app
1个回答
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;

© www.soinside.com 2019 - 2024. All rights reserved.