【问题标题】:yii2 how to keep form data in case of model->save failsyii2如何在模型->保存失败的情况下保留表单数据
【发布时间】:2018-02-20 12:18:14
【问题描述】:

如果模型->保存功能失败,我会丢失我的表单数据。我的表单基于两个不同的模型,因为它们是相互关联的。控制器函数是 actionCreate。

 public function actionCreate()
{
    $model = new Model1();

    if ($model->load(Yii::$app->request->post())) {
        //try to save Model1 in the first step
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $model->save();
            $new_model1_id = $model->id; //id of new inserted company
            // write in model2 second step
            $model2 = new Model2();
            $model2->example1 = $example1;
            $model2->example2 = $example2;
            if ($model2->save()) {
                $transaction->commit();
                return $this->redirect(['index']);
            } else {
                $transaction->rollBack();
                Yii::$app->session->setFlash('error', 'Error!');
                //return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);// return to last page
                return $this->goBack((!empty(Yii::$app->request->referrer) ? Yii::$app->request->referrer : null));
            };
        } catch (Exception $e) {
            $transaction->rollBack();
            Yii::$app->session->setFlash('error', 'Error!');
            //return $this->redirect(Yii::$app->request->referrer ?: Yii::$app->homeUrl);// return to last page
            return $this->goBack((!empty(Yii::$app->request->referrer) ? Yii::$app->request->referrer : null));
        }
    }
    return $this->render('create', [
        'model' => $model,
    ]);

}

当模型保存出错时,我正在尝试返回最后一页。:

return $this->goBack((!empty(Yii::$app->request->referrer) ? Yii::$app->request->referrer : null));

但这不起作用。如何在不丢失所有现有表单条目的情况下分别留在页面上返回页面?

【问题讨论】:

  • 再次渲染页面,不要使用goBack()或任何重定向。让您的代码符合return $this->render(...
  • 你是对的!当然,这将是正确的方法!好像陷入了深深的沉思!谢谢

标签: view yii2 save form-fields


【解决方案1】:

根据 Yupic 的建议,..重新渲染页面即可,不要使用 goBack() 或任何重定向。让您的代码符合 return $this->render(...

【讨论】:

    猜你喜欢
    • 2014-10-15
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多