Recipes by Category

App Distribution (2) Bundle logic, interface and services for distribution. App Logic (37) The Apex programming language, workflow and formulas for logic. Collaboration (6) The Salesforce Chatter collaboration platform. Database (29) Data persistence, reporting and analytics. Integration (33) Web Service APIs and toolkits for integration. Security (9) Platform, application and data security. Tools (4) Force.com tooling User Interface (36) Visualforce MVC and metadata-drive user interfaces. Web Sites (12) Public web sites and apps with optional user registration and login.
Beta Feedback
Cookbook Home » Storing Form Field Values With the Apex 'Cookie' Class

Storing Form Field Values With the Apex 'Cookie' Class

Post by David Wright  (2012-01-23)

Status: Unverified
Level: intermediate

Problem

One of the greatest features provided by Force.com Sites is the ability to develop simple, externally facing web forms that can submit directly to a record in Salesforce.

An example use case for this is a form that allows a user to submit a Case, providing their contact information along with a description of their problem. Because users may frequent the form to submit their issues, collecting their contact information and storing it in a cookie can make future submissions much more quick and convenient.

Apex provides a standard 'Cookie' class that can store this data, however there is a significant limitation: cookie values can only be set in a constructor. This makes setting page cookies difficult because the constructor is executed before the form values are supplied by the user.

Solution

By setting the cookies using an inner class, the form values can be stored upon submission, then easily retrieved when the page is visited on future submissions.

The following code sample shows how you can build a 'Cookie Jar' class into your Apex controller which can be used to store and retrieve form field values:

/*
* Controller extension for submitting a Case on a Sites page
*/
public with sharing class CaseControllerExtension {

    //Case Record From Standard Controller
    public Case newCase {get; set;}

    /* Inner class which does the following:
    *  1. Accepts the form field values as parameters
    *  2. Creates cookies for each passed parameter
    *  3. Uses the setCookies() to store the cookies in the page
    */
    public class cookieJar {
       
        // The controller extension does the work
        public cookieJar(String companyName_c, String email_c, String name_c, String phone_c) {
            
            //Store user's company name
            Cookie companyName = new Cookie('companyName',companyName_c,null,315569260,false);

            //Store user's e-mail address
            Cookie email = new Cookie('email',email_c,null,315569260,false);
        
            //Store user's name
            Cookie name = new Cookie('name', name_c,null,315569260,false);
            
            //Store user's e-mail address
            Cookie phone = new Cookie('phone',phone_c,null,315569260,false);
               
            //Set the page cookies using the setCookies() method
            ApexPages.currentPage().setCookies(new Cookie[]{companyName, email, name, phone});
        }
    
    }//end cookieJar inner class

    //This is the constructor for the Apex extension. 
    //It does the very important job of using the getCookies() method to retrieve previously stored cookies
    public CaseControllerExtension(ApexPages.StandardController controller) {
        
        newCase = (Case)controller.getRecord();
        
        Cookie theCookie;

        theCookie = ApexPages.currentPage().getCookies().get('companyName');
        if(theCookie != null) newCase.SuppliedCompany = theCookie.getValue();
        
        theCookie = ApexPages.currentPage().getCookies().get('email');
        if(theCookie != null) newCase.SuppliedEmail = theCookie.getValue();
        
        theCookie = ApexPages.currentPage().getCookies().get('name');
        if(theCookie != null) newCase.SuppliedName = theCookie.getValue();
        
        theCookie = ApexPages.currentPage().getCookies().get('phone');
        if(theCookie != null) newCase.SuppliedPhone = theCookie.getValue();  

    }
    //This is the final method executed when a user submits the form.
    //It inserts the case, then creates an instance of the inner class, passing the values which will be stored in cookies
    public PageReference finish(){

      //Set this new Case to use the default assignment rules
      Database.DMLOptions dmo = new Database.DMLOptions();
      dmo.assignmentRuleHeader.useDefaultRule = true;
      newCase.setOptions(dmo);
      newCase.Origin = 'Web';
      
      //Insert the case record into the database
      insert newCase;
      //Create an instance of the cookieJar class, passing it the values entered in the form fields
      cookieJar pageCookies = new cookieJar(newCase.SuppliedCompany, newCase.SuppliedEmail, newCase.suppliedName, newCase.SuppliedPhone );
      return new PageReference('/'+ newCase.Id);
    }//end finish method    
}

Discussion

There are three important parts to this code sample:

  1. The inner class constructor accepts a list of parameters, which are then assigned to a new cookie variable and stored in the browser using the setCookies() method.
  2. The constructor within the extension knows what cookie values to look for, and where to assign them. It uses the getCookies() method to grab the cookie values (if they are there) and store them in the approipriate place. By setting the 'newCase' fields equal to the cookie values, those fields will be pre-populated when the page loads.
  3. In the finish() method, after the case is inserted, a new instance of the inner class 'cookieJar' is created. The field values are passed to the constructor of that class, whereupon they are stored in the browser as cookies.

I have found this strategy to be very useful on the many forms I have developed on Sites pages, both for Case and Lead entry. The users of these forms appreciate it as well!

Share

Recipe Activity - Please Log in to write a comment

Nice post ..............

by rao salesforce  (2013-08-27)

Nice Post......Helped me a lot

by Arun Bandl  (2012-09-25)

X

Vote to Verify a Recipe

Verifying a recipe is a way to give feedback to others and broaden your own understanding of the capabilities on Force.com. When you verify a recipe, please make sure the code runs, and the functionality solves the articulated problem as expected.

Please make sure:
  • All the necessary pieces are mentioned
  • You have tested the recipe in practice
  • Have sent any suggestions for improvements to the author

Please Log in to verify a recipe

You have voted to verify this recipe.