yii setflash not working in php [duplicate]

2019-09-18 06:10发布

问题:

This question already has an answer here:

  • yii setflash is not working when using redirect 4 answers

Hye there i have a problem i've design my website using yii framework and now when user register i want to show something like registration successful and redirect to log in page. Unfortunately it keep redirect to log in page without showing any message. Below is my code for user controller

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

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['User']))
    {
        $model->attributes=$_POST['User'];
        if($model->save()) {
            $this->redirect(array('profile'));
            Yii::app()->user->setFlash('success', 'Registration successful. Please login');

        }

    }

    $this->render('create',array(
        'model'=>$model,
    ));
}

This is the code for my log in

public function actionProfile()
{
    $model=$this->loadModel(Yii::app()->user->id);
    unset($model->password);

    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['User']))
    {
        $model->attributes=$_POST['User'];
        if($model->save())
            $this->redirect(array('view','id'=>$model->id));
    }

    $this->render('update',array(
        'model'=>$model,
    ));
}   

This is the code for my access ruler

public function accessRules()
{
    return array(
        array('allow',  // allow all users to perform 'index' and 'view' actions
            'actions'=>array('register','create'),
            'users'=>array('*'),
        ),
        array('allow', // allow authenticated user to perform 'create' and 'update' actions
            'actions'=>array('profile', 'history', 'recommendation','view'),
            'users'=>array('@'),
        ),
        array('allow', // allow admin user to perform 'admin' and 'delete' actions
            'actions'=>array('admin','delete','update','create','index'),
            'expression' => 'Yii::app()->user->isAdmin()'
        ),
        array('deny',  // deny all users
            'users'=>array('*'),
        ),
    );
}

回答1:

    $this->redirect(array('profile'));
    Yii::app()->user->setFlash('success', 'Registration successful. Please login');

You redirect before you set flash... instead try:

    Yii::app()->user->setFlash('success', 'Registration successful. Please login');
    $this->redirect(array('profile'));


回答2:

In your view add this:

<?php if(Yii::app()->user->hasFlash('success')): ?>

<div class="success">
    <?php echo Yii::app()->user->getFlash('success'); ?>
</div>

<?php endif; ?>


标签: php yii