Working with Session Data (Setting and Getting) in SilverStripe 4


Quick tip for using session information in SS4.

This took me a few attempts to figure out. I eventually found the right info deep in the slack channel.

And now reading the documentation again it is there but hidden. It just isn’t as obvious in the docs as it should be because it ends with just the return $this->getRequest()->getSession(); bit which does nothing until you figure out you can add the ->get() or ->set() onto that bit again.

This is for working with submitted forms and filters you want to keep values for the user within custom functions on the Controller.

Get Session Value:
SS3: $value = Session::get(‘MySessionItem’);
SS4: $value = $this->getRequest()->getSession()->get(‘MySessionItem’);

Set Session Value:
SS3: Session::set(‘MySessionItem’, $myValue);
SS4: $this->getRequest()->getSession()->set(‘MySessionItem’, $myValue);

After that the rest of the special calculation form I was working on worked without modification from SS3 to SS4.