yii2 更新后返回上一页
yii2 back to previous page after update
如何在更新记录后将用户重定向到上一页?这是典型的场景:
- 用户在索引页面中过滤结果或对记录分页,然后他们找到他们想要编辑的那个并单击编辑按钮。他们更新该记录的数据,一旦他们点击 "update" 按钮,他们将被重定向到索引视图,但之前选择了 filters/page。
更新后我尝试在我的控制器中使用下面的内容
return $this->redirect('index',302); (this is not what I need)
return $this->redirect(Yii::$app->request->referrer); (this gets user back to update view and not to index view with filters)
return $this->goBack(); (this gets user to homepage)
谢谢!
在您希望用户重定向到的操作中添加
\yii\helpers\Url::remember();
现在在任何控制器中进行下一次调用,例如:
return $this->goBack();
将用户重定向到 "marked" 操作。
我会在典型的更新操作方法中提出以下建议:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if(Yii::$app->request->isGet) {
Url::remember($this->request->referrer, $this->action->uniqueId);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(
Url::previous($this->action->uniqueId) ?: ['view', 'id' => $model->id]
);
}
return $this->render('update', [
'model' => $model,
]);
}
仅当它是 GET 请求(典型的第一次调用)时才会记住 URL,因为如果验证失败,可以再次调用该操作。然后这是一个 POST 调用,您不想记住现在是更新操作本身的引荐来源网址。
保存成功后,您可以重定向到记住的URL。如果由于某种原因没有 URL 被记住,将使用标准(或其他)。
我已经为 URL::remember() and Url::previous(). It should be unique and only gets used in this action. This is the case for $this->action->uniqueId 添加了一个名字。我认为应该这样做,因为用户可以打开多个选项卡,导航到应用程序中的其他地方,并且您可能会使用相同的机制进行更多更新操作。如果未提供唯一名称,则会使用最后记住的 URL,这可能是一个不同的、意外的名称。用户会感到困惑。
与 Bizley 的方法相比,此解决方案在操作本身中 self-contained。其他动作不用记住前面的URL
更新:方案还是有问题,但是可以接受。查看更多here。
如何在更新记录后将用户重定向到上一页?这是典型的场景:
- 用户在索引页面中过滤结果或对记录分页,然后他们找到他们想要编辑的那个并单击编辑按钮。他们更新该记录的数据,一旦他们点击 "update" 按钮,他们将被重定向到索引视图,但之前选择了 filters/page。
更新后我尝试在我的控制器中使用下面的内容
return $this->redirect('index',302); (this is not what I need)
return $this->redirect(Yii::$app->request->referrer); (this gets user back to update view and not to index view with filters)
return $this->goBack(); (this gets user to homepage)
谢谢!
在您希望用户重定向到的操作中添加
\yii\helpers\Url::remember();
现在在任何控制器中进行下一次调用,例如:
return $this->goBack();
将用户重定向到 "marked" 操作。
我会在典型的更新操作方法中提出以下建议:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if(Yii::$app->request->isGet) {
Url::remember($this->request->referrer, $this->action->uniqueId);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(
Url::previous($this->action->uniqueId) ?: ['view', 'id' => $model->id]
);
}
return $this->render('update', [
'model' => $model,
]);
}
仅当它是 GET 请求(典型的第一次调用)时才会记住 URL,因为如果验证失败,可以再次调用该操作。然后这是一个 POST 调用,您不想记住现在是更新操作本身的引荐来源网址。
保存成功后,您可以重定向到记住的URL。如果由于某种原因没有 URL 被记住,将使用标准(或其他)。
我已经为 URL::remember() and Url::previous(). It should be unique and only gets used in this action. This is the case for $this->action->uniqueId 添加了一个名字。我认为应该这样做,因为用户可以打开多个选项卡,导航到应用程序中的其他地方,并且您可能会使用相同的机制进行更多更新操作。如果未提供唯一名称,则会使用最后记住的 URL,这可能是一个不同的、意外的名称。用户会感到困惑。
与 Bizley 的方法相比,此解决方案在操作本身中 self-contained。其他动作不用记住前面的URL
更新:方案还是有问题,但是可以接受。查看更多here。