Monday, June 03, 2013

Setting flash message and redirect with yii-user-management

If you want to set a flash message letting the user know that they need to login or to have required credentials before proceeding to the page they requested, you can do the following.

In the main config file, please add the location of the 'errorHandler'.
 'components' => array(
      'errorHandler'=>array(
            'errorAction' => 'site/error'
        ),

),

Then, in the siteController, add the error action page
/**
     * This is the action to handle external exceptions.
     */
    public function actionError()
    {
        $error = Yii::app()->errorHandler->error;
        if ($error['code']=='403') {
            Yii::app()->user->setFlash('Require Login', $error['code']. 'Error Occured. Please login before continuing.');
            Yii::app()->user->setState('error_login', $error['code']. ' Error Occured. Please login before continuing.');
            /* Get the current URL to redirect */
            Yii::app()->user->setState('redirectUrl', Yii::app()->request->url);
            Yii::app()->controller->redirect(array('/user/user/login'));
        } else if ($error) {
            if ($error['code']=='404') {$error['code'] = "404: Page Not Found"; $error['message'] = "Sorry, but the page you are looking for has not been found.  Please check the URL for errors and try again.";}
            $this->render('error', array('error'=>$error));
        }
        else {
            throw new CHttpException(404, 'Page not found.');
        }
    }
Then, in yii-user-management page, located in app-page/modules/user/views/user/login.php, you can set the flash message to let the users know that they need to login before.

     <?php if(Yii::app()->user->getState('error_login')):?>
        <p class="flash-success"><?php echo Yii::app()->user->getState('error_login'); ?></p>
        <br />

<?php endif; ?>
Then, redirect them to the right page.  If you set the hiddenField for returnURL, yii-user-management will redirect you to the page that the user tried at the first place.

<?php
if(Yii::app()->user->getState('redirectUrl')) {
     $_GET['action'] = Yii::app()->user->getState('redirectUrl');
}
if(isset($_GET['action'])) {
    echo CHtml::hiddenField('returnUrl', urldecode($_GET['action']));
}

?>
I didn't actually use renderFlash used in Yum (yii-user-management), but it works well~

No comments: