Platform Cache In Salesforce

What is Cache?
Cache is a temporary data storing technique. We use Cache to store static data, that is being used frequently in our application for faster performance and better reliability.

What is Platform Cache?
Platform Cache is a memory layer that stores Salesforce session and org data for later access. When we use Platform Cache, the application can run faster because they store reusable data in memory. Application can quickly access this data; they don’t need to duplicate calculations and requests to the database on subsequent transactions. The Platform Cache is like the RAM for the cloud application.

There are two types of Platform Cache:

Session Cache: It stores data for individual user sessions and lives alongside a user session. The maximum life of a session is 8 hours. Session cache expires when its specified time-to-live is reached or when the session expires after eight hours, whichever comes first.

Org Cache: It stores data that any user in an org reuses. Unlike session cache, org cache is accessible across sessions, requests, and org users and profiles. Org cache expires when its specified time-to-live is reached.

When can we use Platform Cache?
We can use Platform Cache, when we want to store temporary data to use in code, but do not want to save it in database. Using cached data improves the performance of the application and is faster than performing SOQL queries repetitively, making multiple API calls, or computing complex calculations.

Platform Cache Considerations:

  • Cache isn’t persisted. There’s no guarantee against data loss.
  • Some or all cache is invalidated when you modify an Apex class in your org.
  • Data in the cache isn’t encrypted.
  • Org cache supports concurrent reads and writes across multiple simultaneous Apex transactions.
  • Session cache doesn’t support asynchronous Apex. Like we can’t use future methods or batch Apex with session cache.
  • The session cache can store values up to eight hours and the org cache can store values up to 48 hours.

Platform Cache Limits:

Cache Allocations by Edition:

  • Developer Edition (0 MB by Default, but can get 10 MB as a trial).
  • Enterprise Edition (10 MB by default)
  • Unlimited Edition (30 MB by default)
  • Performance Edition (30 MB by default)

Session Cache Limits:

  • Maximum size of a single cached item for put() methods (100 KB)
  • Maximum local cache size for a partition, per-request (500 KB)
  • Minimum developer-assigned time-to-live 300 seconds (5 minutes)
  • Maximum developer-assigned time-to-live 28,800 seconds (8 hours)
  • Maximum session cache time-to-live 28,800 seconds (8 hours)

Org Cache Limits:

  • Maximum size of a single cached item for put() methods (100 KB)
  • Maximum local cache size for a partition, per-request (1,000 KB)
  • Minimum developer-assigned time-to-live 300 seconds (5 minutes)
  • Maximum developer-assigned time-to-live 172,800 seconds (48 hours)
  • Default org cache time-to-live 86,400 seconds (24 hours)

Create Partition of Platform Cache:
Go to Setup | Search “Platform Cache” in Quick Find Box | Click Platform Cache

In developer edition, it is 0 MB space default. But we can get 10 MB on click of “Request Trial Capacity” button.

Now Click on “New Platform Cache Partition” to create Partition.

Each partition has one session cache and one org cache segment and you can allocate separate capacity to each segment. Session cache can be used to store data for individual user sessions, and org cache is for data that any users in an org can access.


Note: We cannot delete default Partition. If you want to delete partition, you have to uncheck the default partition option.

Put and retrieve data using Platform cache:
To call Partition in apex code we use namespace.partitionName. local as namespace can be used in both scenario if you have namespace enabled or not enable in your org. In below example I’m using “myPartition” partition.

Store and Retrieve Values from the Session Cache:

Session Cache in Apex Class:

//Add a value to the cache
Integer cartValue = 22;
Cache.Session.put('local.myPartition.CartValue', cartValue);
if (Cache.Session.contains('local.myPartition.CartValue')) {
    Integer cachedCartValue = (Integer)Cache.Session.get('local.myPartition.CartValue');
}

To refer to the default partition and the namespace of the invoking class, we can omit the namespace.partition prefix and specify the key name.

//Use of default partition without namespace and partition
Cache.Session.put('CartValue', 22);
if (Cache.Session.contains('CartValue')) {
    Integer cachedCartValue = (DateTime)Cache.Session.get('CartValue');
}

Session Cache in Visualforce Page:

<apex:outputText value="{!$Cache.Session.local.myPartition.CartValue}"/>

Store and Retrieve Values from the Org Cache:

Org Cache in Apex Class:

//Add a value to the cache
Integer cartValue = 22;
Cache.Org.put('local.myPartition.CartValue', cartValue);
if (Cache.Org.contains('local.myPartition.CartValue')) {
    Integer cachedCartValue = (Integer)Cache.Org.get('local.myPartition.CartValue');
}
//Use of default partition without namespace and partition
Cache.Org.put('CartValue', 22);
if (Cache.Org.contains('CartValue')) {
    Integer cachedCartValue = (DateTime)Cache.Org.get('CartValue');
}

Org Cache in Visualforce Page:

<apex:outputText value="{!$Cache.Org.local.myPartition.CartValue}"/>

Salesforce Apex Switch Statement

From Summer ’18 Release Apex now supports switch statement, that tests whether an expression matches one of several values and branches accordingly.

Syntax:

switch on expression {
    when value1 {		// when block 1
        // code block 1
    }	
    when value2 {		// when block 2
        // code block 2
    }
    when value3 {		// when block 3
        // code block 3
    }
    when else {		  // when else block, optional
        // code block 4
    }
}

Example:

for(Integer i=1; i<=5; i++){
    Switch on i {
        when 1,2{
            System.debug('case 1 and 2');
        }
        when 5{
            System.debug('case 5');
        }
        when else{
            System.debug('case 3 and 4');
        }
    }
 }

The switch statement evaluates the expression and executes the code block for the matching when value. If no value matches, the code block for the when else block is executed. If there isn’t a when else block, no action is taken.

Lightning OverlayLibrary Modal

In Spring 18 Salesforce has provided lightning:overlayLibrary tag to displays messages via modals and popovers. This component requires API version 41.0 and later. lightning:overlayLibrary is not supported in the lightning application. It’s supported only on salesforce lightning experience Lightning, Console, Communities.

In this example, I’m using below components:

Main Component (Sample.cmp) – Will contain lightning:overlayLibrary tag with aura:id attribute and a lightning:button
Modal Content (OverlayLibraryModal.cmp) – The component responsible for containing all the content to show in the Modal as content.

Sample.cmp:

<!--Sample.cmp--> 
<aura:component  implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome" access="global">
    <!--Declare Attribute-->
    <aura:attribute name="FirstName" type="String"/> 
    <aura:attribute name="LastName" type="String"/> 
    
    <lightning:overlayLibrary aura:id="overlayLib"/>
    
    <!--Component Start-->    
    <div class="slds-m-around--xx-large">
        <lightning:input name="fname" label="First Name" value="{!v.FirstName}" />
        <lightning:input name="lname" label="Last Name" value="{!v.LastName}" />
        <br/>
        <lightning:button variant="brand" label="Show Modal" onclick="{!c.handleShowModal}"/>
    </div>
    <!--Component End-->
</aura:component>

SampleController.js:

({
    handleShowModal: function(component) {
        var fName = component.get("v.FirstName");
        var lName = component.get("v.LastName");
        $A.createComponent("c:OverlayLibraryModal",
                           {
                               "FirstName" : fName,
                               "LastName" : lName
                           },
                           function(content, status) {
                               if (status === "SUCCESS") {
                                   var modalBody = content;
                                   component.find('overlayLib').showCustomModal({
                                       header: "Welcome to Biswajeet Samal's Blog",
                                       body: modalBody, 
                                       showCloseButton: true,
                                       closeCallback: function(ovl) {
                                           console.log('Overlay is closing');
                                       }
                                   }).then(function(overlay){
                                       console.log("Overlay is made");
                                   });
                               }
                           });
    }
})

OverlayLibraryModal.cmp:

<aura:component access="global">
    <!--Declare Attribute-->
    <aura:attribute name="FirstName" type="String"/> 
    <aura:attribute name="LastName" type="String"/> 
    <lightning:overlayLibrary aura:id="overlayLib"/>
    
    <!--Component Start-->  
    <div class="slds-m-around--xx-large">
        <p>{!v.FirstName} &nbsp; {!v.LastName} </p>
        <br/>
        <lightning:button variant="brand" label="Cancel" onclick="{!c.handleCloseModal}"/>
    </div>
    <!--Component End-->
</aura:component>

OverlayLibraryModalController.js:

({
    handleCloseModal: function(component, event, helper) {
        //Close the Modal Window
        component.find("overlayLib").notifyClose();
    }
})

Output:

Salesforce Lightning Datatable

Apex Controller:

public class SampleAuraController {
    
    //Get Contact List
    @AuraEnabled
    public static List<Contact> getContactList(Integer recordLimit, Integer recordOffset){
        Integer intLimit = Integer.valueof(recordLimit);
        Integer intOffset = Integer.valueof(recordOffset);
        List<Contact> conList = new List<Contact>();
        conList = [SELECT Id, Name, Email, Phone FROM Contact LIMIT :intLimit Offset :intOffset];
        return conList;
    }
    
    //Get Total Number of Contacts
    @AuraEnabled
    public static Integer getTotalContacts(){
        AggregateResult results = [SELECT Count(Id) TotalContacts  From Contact];
        Integer totalContacts = (Integer)results.get('TotalContacts') ; 
        return totalContacts;
    } 
    
    //Delete Contact
    @AuraEnabled
    public static void deleteContact(Contact con){
        Delete con;
    } 
}

Lightning Component:

<!--Sample.cmp--> 
<aura:component controller="SampleAuraController" implements="flexipage:availableForAllPageTypes,force:appHostable">
    
    <!--Declare Attributes-->
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="selectedRowsCount" type="Integer" default="0"/>
    <aura:attribute name="selectedRowsDetails" type="Object" />
    <aura:attribute name="selectedRowsList" type="List" />
    <aura:attribute name="maxRowSelection" type="Integer" default="10"/>
    <aura:attribute name="selectedRows" type="List" />
    <aura:attribute name="enableInfiniteLoading" type="Boolean" default="true"/>
    <aura:attribute name="initialRows" type="Integer" default="10"/>
    <aura:attribute name="rowsToLoad" type="Integer" default="10"/>
    <aura:attribute name="totalNumberOfRows" type="Integer" default="10"/>
    <aura:attribute name="loadMoreStatus" type="String" default="Please scroll down to load more data"/>
    <aura:attribute name="showRowNumberColumn" type="Boolean" default="false"/>
    <aura:attribute name="rowNumberOffset" type="Integer" default="0"/>
    <aura:attribute name="rowsToAdd" type="Integer" default="10"/>
    <aura:attribute name="currentCount" type="Integer" default="10"/>
    <aura:attribute name="sortedBy" type="String"/>
    <aura:attribute name="sortedDirection" type="String"/>
    <aura:attribute name="defaultSortDirection" type="String"/>
    
    <!--Declare Handlers-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <!--Component Start-->
    <div class="slds-m-around_xx-large" style="height: 300px">
        <lightning:datatable columns="{!v.columns}"
                             data="{!v.data}"
                             keyField="Id"
                             showRowNumberColumn="true"
                             rowNumberOffset="0"
                             onrowaction="{!c.handleRowAction}"
                             selectedRows="{!v.selectedRows}"
                             maxRowSelection="{!v.maxRowSelection}"
                             onrowselection="{!c.handleSelectedRow}"
                             enableInfiniteLoading="true"
                             loadMoreOffset="{!v.loadMoreOffset}"
                             sortedBy="{!v.sortedBy}"
                             sortedDirection="{!v.sortedDirection}"
                             defaultSortDirection="{!v.defaultSortDirection }"
                             onsort="{!c.handleColumnSorting}"
                             onloadmore="{!c.handleLoadMoreContacts}"/>
        <br/>
        <div class="slds-float_left">
            <strong>Total Rows : {!v.totalNumberOfRows}</strong>
            &nbsp;&nbsp;
            <strong>Selected Rows: {!v.selectedRowsCount }</strong>
        </div>
        <div class="slds-float_right">
            <strong>{!v.loadMoreStatus}</strong>
        </div>
        <br/>
        <br/>
        <div class="slds-float_left">
            <lightning:button label="Get Selected Contacts"  variant="brand" onclick="{!c.handleSelectedRows}"/>    
        </div>
    </div>
    <!--Component End-->
</aura:component>

Lightning Component JS Controller:

({
    doInit : function(component, event, helper) {
        helper.getTotalNumberOfContacts(component);
        helper.getColumnAndAction(component);
        helper.getContacts(component);
    },
    
    handleLoadMoreContacts: function (component, event, helper) {
        event.getSource().set("v.isLoading", true);
        component.set('v.loadMoreStatus', 'Loading....');
        helper.getMoreContacts(component, component.get('v.rowsToLoad')).then($A.getCallback(function (data) {
            if (component.get('v.data').length == component.get('v.totalNumberOfRows')) {
                component.set('v.enableInfiniteLoading', false);
                component.set('v.loadMoreStatus', 'No more data to load');
            } else {
                var currentData = component.get('v.data');
                var newData = currentData.concat(data);
                component.set('v.data', newData);
                component.set('v.loadMoreStatus', 'Please scroll down to load more data');
            }
            event.getSource().set("v.isLoading", false);
        }));
    },
    
    handleSelectedRows: function (component, event, helper) {
        var data = component.get('v.data');
        var selectedRowList =  component.get("v.selectedRowsList");
        console.log('selectedRowList-' + selectedRowList);
    },
    
    handleSelectedRow: function(component, event, helper){
        var selectedRows = event.getParam('selectedRows');
        component.set("v.selectedRowsCount", selectedRows.length);
        let obj =[] ; 
        for (var i = 0; i < selectedRows.length; i++){
            obj.push({Name:selectedRows[i].Name});
        }
        component.set("v.selectedRowsDetails", JSON.stringify(obj) );
        component.set("v.selectedRowsList", event.getParam('selectedRows'));
    },
    
    handleRowAction: function (component, event, helper) {
        var action = event.getParam('action');
        switch (action.name) {
            case 'new':
                helper.createContactRecord(component, event);
                break;
            case 'edit':
                helper.editContactRecord(component, event);
                break;
            case 'delete':
                helper.deleteContactRecord(component, event);
                break;
            case 'view':
                helper.viewContactRecord(component, event);
                break;
        }
    },
    
    handleColumnSorting: function (component, event, helper) {
        var fieldName = event.getParam('fieldName');
        var sortDirection = event.getParam('sortDirection');
        component.set("v.sortedBy", fieldName);
        component.set("v.sortedDirection", sortDirection);
        helper.sortData(component, fieldName, sortDirection);
    },
})

Lightning Component JS Helper:

({
    getContacts : function(component) {
        var action = component.get("c.getContactList");
        action.setParams({
            "recordLimit": component.get("v.initialRows"),
            "recordOffset": component.get("v.rowNumberOffset")
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS" ) {
                var resultData = response.getReturnValue();
                component.set("v.data", resultData);
                component.set("v.currentCount", component.get("v.initialRows"));
            }
        });
        $A.enqueueAction(action);
    },
    
    getTotalNumberOfContacts : function(component) {
        var action = component.get("c.getTotalContacts");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS" ) {
                var resultData = response.getReturnValue();
                component.set("v.totalNumberOfRows", resultData);
            }
        });
        $A.enqueueAction(action);
    },
    
    getColumnAndAction : function(component) {
        var actions = [
            {label: 'New', name: 'new'},
            {label: 'Edit', name: 'edit'},
            {label: 'Delete', name: 'delete'},
            {label: 'View', name: 'view'}
        ];
        component.set('v.columns', [
            {label: 'Name', fieldName: 'Name', type: 'text', sortable:true},
            {label: 'Email', fieldName: 'Email', type: 'email', sortable:true},
            {label: 'Phone', fieldName: 'Phone', type: 'phone', sortable:true},
            {type: 'action', typeAttributes: { rowActions: actions } } 
        ]);
    },
    
    getMoreContacts: function(component , rows){
        return new Promise($A.getCallback(function(resolve, reject) {
            var action = component.get('c.getContactList');
            var recordOffset = component.get("v.currentCount");
            var recordLimit = component.get("v.initialRows");
            action.setParams({
                "recordLimit": recordLimit,
                "recordOffset": recordOffset 
            });
            action.setCallback(this, function(response) {
                var state = response.getState();
                if(state === "SUCCESS"){
                    var resultData = response.getReturnValue();
                    resolve(resultData);
                    recordOffset = recordOffset+recordLimit;
                    component.set("v.currentCount", recordOffset);   
                }                
            });
            $A.enqueueAction(action);
        }));
    },
    
    sortData: function (component, fieldName, sortDirection) {
        var data = component.get("v.data");
        var reverse = sortDirection !== 'asc';
        data.sort(this.sortBy(fieldName, reverse))
        component.set("v.data", data);
    },
    
    sortBy: function (field, reverse, primer) {
        var key = primer ?
            function(x) {return primer(x[field])} :
        function(x) {return x[field]};
        reverse = !reverse ? 1 : -1;
        return function (a, b) {
            return a = key(a), b = key(b), reverse * ((a > b) - (b > a));
        }
    },
    
    viewContactRecord : function(component, event) {
        var row = event.getParam('row');
        var recordId = row.Id;
        var navEvt = $A.get("event.force:navigateToSObject");
        navEvt.setParams({
            "recordId": recordId,
            "slideDevName": "detail"
        });
        navEvt.fire();
    },
    
    deleteContactRecord : function(component, event) {
        var action = event.getParam('action');
        var row = event.getParam('row');
        
        var action = component.get("c.deleteContact");
        action.setParams({
            "con": row
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS" ) {
                var rows = component.get('v.data');
                var rowIndex = rows.indexOf(row);
                rows.splice(rowIndex, 1);
                component.set('v.data', rows);
                
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Success!",
                    "message": "The record has been delete successfully."
                });
                toastEvent.fire();
            }
        });
        $A.enqueueAction(action);
    },
    
    editContactRecord : function(component, event) {
        var row = event.getParam('row');
        var recordId = row.Id;
        var editRecordEvent = $A.get("e.force:editRecord");
        editRecordEvent.setParams({
            "recordId": recordId
        });
        editRecordEvent.fire();
    },
    
    createContactRecord : function (component, event) {
        var createRecordEvent = $A.get("e.force:createRecord");
        createRecordEvent.setParams({
            "entityApiName": "Contact"
        });
        createRecordEvent.fire();
    }
})

Output:

Salesforce Lightning Button Menu

Lightning Component:

<!--Sample.cmp--> 
<aura:component implements="flexipage:availableForAllPageTypes, force:appHostable">
    <div class="slds-m-around_xx-large">
        <lightning:buttonMenu  iconName="utility:settings" alternativeText="Action" onselect="{!c.handleMenuSelect}">
            <lightning:menuItem label="New" iconName="utility:new" value="new"/>
            <lightning:menuItem label="Edit" iconName="utility:edit" value="edit"/>
            <lightning:menuItem label="Delete" iconName="utility:delete" value="delete"/>
        </lightning:buttonMenu>
    </div>
</aura:component>

Lightning Component JS Controller:

({    
    handleMenuSelect: function(component, event, helper) {
        var selectedMenu = event.detail.menuItem.get("v.value");
        console.log('selectedMenu-' + selectedMenu);
        switch(selectedMenu) {
            case "new":
                //do create
                break;
            case "edit":
                //do edit
                break;
            case "delete":
                //do delete
                break;
        }
    }
})

Output:

Reference: lightning:buttonMenu lightning:menuItem