Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Customising the CMS /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Session variable not working properly


Go to End


4 Posts   985 Views

Avatar
Optic Blaze

Community Member, 190 Posts

24 October 2015 at 3:18am

Edited: 24/10/2015 3:18am

Hi there, i want to pass a variable to my controller and then use that to set a session variable. I have managed to get it to work, but it only seems to work on pages that inherit from the page class and not the page class itself. So if i have a pagetype call MyPage that inherits from Page...this code works...if i try and use it on the home page for example...it fails. Any ideas?

class Page_Controller extends ContentController {
	private static $allowed_actions = array (
	'MyUrl'
	);
	public function init() {
			parent::init();		
	}
		
	public function MyUrl() {
		$x = $_GET['myurl1'];
		if (isset($x)) {Session::set('MySession', $x);}
		$y = Session::get('MySession');
		return $y;
		}
}

Avatar
Optic Blaze

Community Member, 190 Posts

2 November 2015 at 10:28pm

Anyone got some ideas?

Avatar
helenclarko

Community Member, 166 Posts

4 November 2015 at 9:04am

Hi Optic Blaze,

Just a thought, have you tried the following:

class Page_Controller extends Page_Controller {
	private static $allowed_actions = array (
	'MyUrl'
	);
	public function init() {
			parent::init();		
	}
		
	public function MyUrl() {
		$x = $_GET['myurl1'];
		if (isset($x)) {Session::set('MySession', $x);}
		$y = Session::get('MySession');
		return $y;
		}
}

-helenclarko

Avatar
Optic Blaze

Community Member, 190 Posts

4 November 2015 at 12:28pm

Hi Helenclarko,

Thanks for the reply. I cant extend using page controller since page_controller needs to extend off content_controller. When you try it you will find that the site breaks. I however did figure out the problem...my code was initiating too late in the sequence. I needed to move the session variable declaration into the init section of the code so that it is the first thing that initiates. The following works:

 

class Page_Controller extends Page_Controller {
	private static $allowed_actions = array (
	'MyUrl'
	);
	public function init() {
			parent::init();
        /// Set session variable
       		$x = $_GET['myurl1'];
		if (isset($x)) {Session::set('MySession', $x);}
	}
		
	public function MyUrl() {
		return Session::get('MySession');
		}
}