繁体   English   中英

在yii2中的afterSave重定向

[英]afterSave redirect in yii2

我的模型中有一个afterSave函数,它根据用户给出的开始时间和持续时间保存某些服务的到期日期。 我的afterSave工作正常,但在保存模型而不是显示空白页面后,它没有被重定向。

模型:

public function afterSave($insert)
{

    $month= "+".$this->duration_in_months." month";
    $this->exp_date=date("Y-m-d H:i:s",strtotime($month));
    $this->save(['exp_date']);

    return parent::afterSave($insert);
} 

控制器:

if($model->save())

    return $this->redirect(['view', 'id' => $model->sub_id]);

} 

我如何重定向afterSave?提前感谢!

正确的方法是从Controller调用save() ,它将隐式调用afterSave()

你只需要在Controller-Action中执行此操作 -

if($model->save()) { $this->redirect(......); }

您的控制器没问题,但我在“afterSave”方法中看到了一些奇怪的东西。

$this->save(['exp_date'])

首先,标准的ActiveRecord“save”必须将boolean作为其第一个参数。 接下来你将在这里获得递归 - 因为在“save”方法中调用了“afterSave”方法。

所以我认为真正的问题是你没有显示任何错误。 在包含Yii之前,尝试在index.php中启用错误报告:

error_reporting(E_ALL);
ini_set('display_errors', '1');
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

这仅用于开发。

您可以使用\\Yii::$app->response->redirect('url')->send()从任何地方进行重定向。

您的应用程序显示空白页面,因为您在afterSave()调用$this->save(['exp_date']) afterSave() 它再次调用afterSave()并导致无限循环。 你应该避免这种情况。

我有同样的问题。 但它解决了以下问题:

public function afterSave($insert, $changedAttributes)
{
    parent::afterSave($insert, $changedAttributes);

    if ($insert) {
        $month = "+".$this->duration_in_months." month";
        $this->exp_date = date("Y-m-d H:i:s", strtotime($month));
        $this->save(false, ['exp_date']);
    }
}

尝试return $this->redirect();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM