简体   繁体   English

在yii2中的afterSave重定向

[英]afterSave redirect in yii2

I have an afterSave function in my model which saves the expiry date of some service based on the start period and duration given by the user. 我的模型中有一个afterSave函数,它根据用户给出的开始时间和持续时间保存某些服务的到期日期。 My afterSave works fine,but it is not getting redirected after saving the model instead showing a blank page. 我的afterSave工作正常,但在保存模型而不是显示空白页面后,它没有被重定向。

Model: 模型:

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);
} 

Controller: 控制器:

if($model->save())

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

} 

How can i redirect afterSave?Thanks in advance! 我如何重定向afterSave?提前感谢!

Proper way is to call the save() from the Controller, which will call the afterSave() implicitly. 正确的方法是从Controller调用save() ,它将隐式调用afterSave()

You only have to do this in the Controller-Action - 你只需要在Controller-Action中执行此操作 -

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

Your controller is OK, but I see something odd in your "afterSave" method. 您的控制器没问题,但我在“afterSave”方法中看到了一些奇怪的东西。 There is

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

First of all standard ActiveRecord "save" must have boolean as its first argument. 首先,标准的ActiveRecord“save”必须将boolean作为其第一个参数。 Next is you will get recursion here - as "afterSave" method is being called inside "save" method. 接下来你将在这里获得递归 - 因为在“save”方法中调用了“afterSave”方法。

So I suppose the real problem is that you don't have any error displayed. 所以我认为真正的问题是你没有显示任何错误。 Try to enable error reporting in your index.php before including Yii: 在包含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');

This is only for development. 这仅用于开发。

You can use \\Yii::$app->response->redirect('url')->send() for redirection from everywhere. 您可以使用\\Yii::$app->response->redirect('url')->send()从任何地方进行重定向。

Your application shows blank page because you call $this->save(['exp_date']) in afterSave() . 您的应用程序显示空白页面,因为您在afterSave()调用$this->save(['exp_date']) afterSave() It calls afterSave() again and causes endless loop. 它再次调用afterSave()并导致无限循环。 You should avoid this. 你应该避免这种情况。

I had the same problem. 我有同样的问题。 But it was resolved in the following: 但它解决了以下问题:

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