Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

afterSave redirect in yii2

Tags:

php

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. My afterSave works fine,but it is not getting redirected after saving the model instead showing a blank page.

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!

like image 863
Dency G B Avatar asked Nov 01 '22 00:11

Dency G B


2 Answers

Proper way is to call the save() from the Controller, which will call the afterSave() implicitly.

You only have to do this in the Controller-Action -

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

like image 65
Kunal Dethe Avatar answered Nov 09 '22 03:11

Kunal Dethe


Your controller is OK, but I see something odd in your "afterSave" method. There is

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

First of all standard ActiveRecord "save" must have boolean as its first argument. Next is you will get recursion here - as "afterSave" method is being called inside "save" method.

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:

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.

like image 29
Pavel Bariev Avatar answered Nov 09 '22 03:11

Pavel Bariev