Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
in Salesforce by (11.9k points)

 want to be able to read / write some variables to the current session in my Salesforce site pages.

I have a site built using Salesforce Sites, I need to store/retrieve some values across all the pages (consider that I am building something similar to a shopping cart). However I cant find any good example on how to read and write variables to the session (anonymous user).

I am using Visualforce pages with several controllers built in Apex.


1 Answer

0 votes
by (32.1k points)

Custom settings are basically cached at the application level. I'm not sure if I'd recommend that approach, but you might be able to get it to work.

If you create a Custom Setting named "SessionData", and add your custom fields (which symbolizes the data you want to store in session), you could save data to it like this:

Database.SaveResult result = Database.insert(new SessionData__c(YourFieldHere='Your value here etc'));


Then you can use the resulting custom setting ID to store in a cookie. While custom settings can be obtained using normal SOQL, the major advantage is that the data is cached and can be accessed like this:

if (SessionData__c.getAll().containsKey('unique ID from cookie here'))


     System.debug(SessionData__c.getInstance('unique ID from cookie here').YourFieldHere);


Note: Custom settings aren't designed for this, so you'll need to periodically purge old custom settings data, as normal session management systems do.

To learn in-depth about Salesforce, sign up for an industry based Salesforce Certification.

Browse Categories