Adding login form to each page

You are viewing revision #1 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#2) »

After adding proper form to the main layout, like:

...
if(Yii::app()->user->isGuest):
  echo CHtml::beginForm(array('site/login'));
  ...

You may recognize that the user does not get redirected to the previous page correctly.

This is because CWebUser::loginRequired() is not invoked, thus proper states are not saved before the user logs in.

If you want to preserve the referrer you can attach an event handler to your application onEndRequest event with the following content:

$app=Yii::app();
if($app->createUrl($app->user->loginUrl[0])!=$app->request->getUrl())
	$app->user->setReturnUrl(Yii::app()->request->getUrl());

The above code does the following: if the user is at the login page, the referrer is not saved for future reference (otherwise he will be redirected to the login page right after he logged in, which is, of course, not the desired effect).

In any other cases, the previously viewed page is reloaded if the user logs in with the form in the header.

Make sure your login action makes use of this:

$this->redirect(Yii::app()->user->returnUrl);

Your logout process might also use this feature and not send the user back to the front page.

If you are not sure how to attach an event handler to your application object, open up your config file and insert this function at the head of the code (before returning the array):

function endRequest($event)
{
	$app=Yii::app();
	if($app->createUrl($app->user->loginUrl[0])!=$app->request->getUrl())
		$app->user->setReturnUrl(Yii::app()->request->getUrl());
}

Attaching could be done in your config:

return array(
...
	'onEndRequest'=>'endRequest',
...
3 1
7 followers
Viewed: 38 902 times
Version: Unknown (update)
Category: Tutorials
Written by: pestaa
Last updated by: Yang He
Created on: Aug 23, 2009
Last updated: 5 years ago
Update Article

Revisions

View all history

Related Articles