Yii2 删除请求 POST 的记录
Yii2 Delete record with request POST
如何使用请求 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 删除。
像这样设置删除按钮
<?= Html::a('Delete', ['user/delete', 'id' => $user->id], [
'class' => 'btn btn-danger',
'data-confirm' => 'Are you sure?',
'data-method' => 'post',
]) ?>
而Htmlclass是
使用yii\helpers\Html;
如何使用请求 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 删除。
像这样设置删除按钮
<?= Html::a('Delete', ['user/delete', 'id' => $user->id], [
'class' => 'btn btn-danger',
'data-confirm' => 'Are you sure?',
'data-method' => 'post',
]) ?>
而Htmlclass是
使用yii\helpers\Html;