Saturday, November 24, 2018

Integration Patterns and Best Practices for Salesforce - Part 2

This is my second blog to explain Integration patterns and best practices.  In this I will cover remaining patterns.

In order to understand the patterns covered in previous blog, refer below link:
Integration Patterns and Best Practices for Salesforce - Part 1

If you are planning to appear for "SALESFORCE CERTIFIED INTEGRATION ARCHITECTURE DESIGNER" exam then below information will be helpful.

Note: I have summarized the information provided in Integration Patterns and Practices documentation provided by salesforce in this blog.

Batch Data Synchronization

Use this pattern if you want to import data into Salesforce and export data out of Salesforce, taking into consideration that these imports and exports can interfere with end-user operations during business hours, and involve large amounts of data.
Below are different scenarions which can utilize this pattern:
  • Extract and transform accounts, contacts, and opportunities from the current CRM system and load the data into Salesforce (initial  data import).
  • Extract, transform, and load customer billing data into Salesforce from a remote system on a weekly basis (ongoing).
  • Extract customer activity information from Salesforce and import it into an on-premises data warehouse on a weekly basis (ongoing backup).      
Change data capture    
  • If remote system is master
Leverage a third-party ETL tool that allows you to run change data capture against source data. The tool reacts to changes in the source data set, transforms the data, and then calls Salesforce Bulk API to issue DML statements. This can also be implemented using the Salesforce SOAP API.  
  • If Salesforce system is master
If Salesforce is the data source then you can use time/status information on individual rows to query the data and  filter the target result set. This can be implemented by using SOQL together with SOAP API and the query() method, or by the using SOAP API and the getUpdated() method.

In case of using middleware, it is recommend that you create the control tables and associated data structures in an environment that the ETL tool has access. This provides adequate levels of resilience. Salesforce should be treated as a spoke in this process and the ETL infrastructure is the hub.
For an ETL tool to gain maximum benefit from data synchronization capabilities, consider the following:
  • Chain and sequence the ETL jobs to provide a cohesive process.
  • Use primary keys from both systems to match incoming data.
  • Use specific API methods to extract only updated data.
  • If importing child records in a master-detail or lookup relationship, group the imported data using its parent key at the source to avoid locking. For example, if you’re importing contact data, be sure to group the contact data by the parent account key so that maximum number of contacts for a single account can be loaded in one API call. Failure to group the imported data usually results in the first contact record being loaded and subsequent contact records for that account to fail in the context of the API call.
  •  Any post-import processing, such as triggers, should only process data selectively.
Error Handling and Recovery
  • Exporting data from SFDC
During read operation from salesforce, middleware should perform below operations
  • Log the error
  • Retry the read operation
  • Terminate if unsuccessful
  • Send a notification
  • Importing data into SFDC
Handling—Errors that occur during a write operation via middleware can result from a combination of factors in the application (record locking errors). The API calls return a result set that consists of the information listed below. This information should be used to retry the write operation (if necessary).
  • Record identifying information
  • Success/failure notification
  • collection of errors for each record
Security Considerations
  • A Lightning Platform license is required to allow authenticated API access to the Salesforce API.
  • It is recommended to use standard encryption to keep password access secure.
  • Use the HTTPS protocol when making calls to the Salesforce APIs. You can also proxy traffic to the Salesforce APIs through an on-premises security solution, if necessary.

Timeline is not significant factor as these operations runs in background. Loading batches during business hours might result in some contention, resulting in either a user's update failing, or more significantly, a batch load (or partial batch load) failing.
For organizations that have global operations, it might not be feasible to run all batch processes at the same time because the system might continually be in use. Data segmentation techniques using record types and other filtering criteria can be used to avoid data contention in these cases.

Data Volumes

This pattern is mainly used for bulk data import and export.

Remote Call-In

This pattern is used when remote system wants to connect to salesforce and after authentication, want to update records in SFDC.
Below are different options available for this:
Query, Create update or delete records and obtain metadata information from Salesforce
Salesforce provides two WSDLs for remote systems:
  • Enterprise WSDL—Provides a strongly-typed WSDL that’s specific to a Salesforce organization.
  • Partner WSDL—Contains a loosely-typed WSDL that’s not specific to a Salesforce organization. It deals with considering subject structure.
Security :- The client executing SOAP API must have a valid login and obtain a session to perform any API calls. The API respects object-level and field-level security configured in the application based on the logged in user’s profile.
Data Volume :- For bulk data operations (more than 500,000 records), use the REST-based Bulk API.
Query, Create update or delete records and obtain metadata information from Salesforce
REST exposes resources (entities/objects) as URIs and uses HTTP verbs to define CRUD perations on these resources. Unlike SOAP, the REST API requires no predefined contract, utilizes XML and JSON for responses, and has loose typing. REST API is lightweight and provides a simple method for interacting with Salesforce. Its advantages include ease of integration and development, and it’s an excellent choice for use with mobile applications and Web 2.0 projects.
Security:-  We recommend that the remote system establish an OAuth trust for authorization.  It’s also possible to make REST calls with a valid session ID that might have been obtained by other means (for example, retrieved by calling SOAP API or provided via an outbound message).
We recommend that clients that call the REST API cache and reuse the session ID to maximize performance, rather than obtaining a new session ID for each call.
  • Custom Webservices/Apex Rest classes
We can create custom webservices and provide WSDL to remote system so that they can consume it and call custom webservices methods. If we create Apex rest services, then remote system can directly call URI’s.
Custom webservices or Apex Rest services are usefull when you need to update multiple records related to different objects in single call as logic for complete transaction is controlled by developer.
  • Bulk API
Bulk API is based on REST principles, and is optimized for loading or deleting large sets of data. It has the same accessibility and security behavior as REST API.
Bulk API allows the client application to query, insert, update, upsert, or delete a large number of records asynchronously by submitting a number of batches, which are processed in the background by Salesforce. In contrast, SOAP API is optimized for real-time client applications that update small numbers of records at a time.
Although SOAP API can also be used for processing large numbers of records, when the data sets contain hundreds of thousands to millions of records, it becomes less practical. This is due to its relatively high overhead and lower performance characteristics.

Error Handling and Recovery

Error handling needs to be implemented by remote system or middleware. Middleware or remote system should implement retry logic and also need to make sure that duplicate request is coming to salesforce. We can handle duplicate request in case of custom webservices or apex rest services but it is required for remote system to have some mechanism for this.


SOAP and REST API’s are synchronous.

Data Volume

  • Login—The login request size is limited to 10 KB or less.
  • Create, Update, Delete—The remote system can create, update, or delete up to 200 records at a time. Multiple calls can be made to process more than a total of 200 records, but each request is limited to 200 records in size.
  • Query Results Size — By default, the number of rows returned in the query result object (batch size), returned in a query() or queryMore() call is set to 500. Where the number of rows to be returned exceeds the batch size, use the queryMore() API call to iterate through multiple batches. The maximum batch size is 2,000 records
Bulk API is synchronous when submitting the batch request and associated data. The actual processing of the data occurs asynchronously in the background.
  • Up to 2,000 batches can be submitted per rolling 24–hour period.
  • A batch can contain a maximum of 10,000 records.

UI Update Based on Data Changes

When an event occurs in Salesforce like update to any record, user should be notified in the Salesforce user interface without having to refresh their screen and potentially losing work.
The recommended solution to this integration problem is to use the Salesforce Streaming API.
This solution is comprised of the following  components:
  • A PushTopic with a query definition that allows you to:
    • Specify what events trigger an update
    • Select what data to include in the notification
  • A JavaScript-based implementation of the Bayeux protocol (currently CometD) that can be used by the user interface
  • A Visualforce page
  • A JavaScript library included as a static resource
Benefit of Streaming API
  • No need to write pooling mechanism to identify the records changes
  • User does not have to refresh record or invoke any action to get latest updates
    • Delivery of notifications isn’t guaranteed.
    • Order of notifications isn’t guaranteed.
    • Notifications aren’t generated from record changes made by Bulk API.
      Security Considerations

      It respect Salesforce organization-level security.

      Idempotent Design Considerations
      • Remote Process Invocation—Request and Reply / Request and Forget
      It’s important to ensure that the remote procedure being called is idempotent means it can identify if any repeated request is coming to avoid duplicates request processing. It’s almost impossible to guarantee that Salesforce only calls once, especially if the call is triggered from a user interface event. Even if Salesforce makes a single call, there’s no guarantee that other processes (for example, middleware) do the same.
      The most typical method of building an idempotent receiver is for it to track duplicates based on unique message identifiers sent by the consumer. Apex web service or REST calls must be customized to send a unique message ID.
      • Remote Call In
      The remote system must manage multiple (duplicate) calls, in the case of errors or timeouts, to avoid duplicate inserts and redundant updates (especially if downstream triggers and workflow rules fire). While it’s possible to manage some of these situations within Salesforce (particularly in the case of custom SOAP and REST services), we recommend that the remote system (or middleware) manages error handling and idempotent design.

      Hope this will help!!

      Friday, November 23, 2018

      Integration Patterns and Best Practices for Salesforce - Part 1

      Whenever you have to integrate Salesforce with remote system, then you need to consider different integration scenarios and API’s availability. Integration patterns helps you identify the correct pattern or API to build robust framework for integration.

      If you are planning to appear for "SALESFORCE CERTIFIED INTEGRATION ARCHITECTURE DESIGNER" exam then below information will be helpful.

      In complex integration scenarios, mix of integration patterns is used by weighing pros and cons accordingly.

      Today I am going to cover below patterns. For remaining patterns, refer below blog:
      Integration Patterns and Best Practices for Salesforce - Part 2

      Remote Process Invocation—Request and Reply

      This pattern is used when you need to call remote system and wait for response. After getting response you want to update something in SFDC in synchronous manner. This pattern is used when you want to complete request and process the response in same transaction.

      Different Scenarios:
      • Onclick of button in UI :- In VF page, onclick of button you want to call remote system to get order information and display it to user on VF page without storing it in salesforce. You can implement this with Apex SOAP or REST callouts.
      • Apex triggers :-You can use Apex triggers to perform callouts based on record data changes. All calls made from within the trigger context must execute asynchronously from the initiating event. Therefore, apex triggers isn’t recommended for this pattern.
      • Batch Class :- You can make calls to a remote system from a batch job. This solution allows batch remote process execution and processing of the response from the remote system in Salesforce. However, a given batch has limits to the number of calls. So, batch class is also not recommended for this pattern.
      Error Handling and Recovery

      It’s important to include an error handling and recovery strategy as part of the overall solution.
      • Error handling—When an error occurs (exceptions or error codes are returned to the caller), the caller manages error handling. For example, an error message displayed on the end-user’s page or logged to a table requiring further action.
      • Recovery—Changes aren’t committed to Salesforce until the caller receives a successful response. For example, the order status isn’t updated in the database until a response that indicates success is received. If necessary, the caller can retry the operation.
      Security Considerations

      Any call to a remote system must maintain the confidentiality, integrity, and availability of the request. The following security considerations are specific to using Apex SOAP and HTTP calls in this pattern.
      • One-way SSL is enabled by default (for apex callout and outbound messages), but two-way SSL is supported with both self-signed and CA-signed certificates to maintain authenticity of both the client and server.
      • Salesforce does not currently support WS-Security.
      • Where necessary, consider using one-way hashes or digital signatures using the Apex Crypto class methods to ensure request integrity.
      • The remote system must be protected by implementing the appropriate firewall mechanisms.

      Timeliness is of significant importance in this pattern. Usually:
      • The request is typically invoked from the user interface, so the process must not keep the user waiting.
      • Salesforce has a configurable timeout of up to 60 seconds for calls from Apex.
      • Completion of the remote process is executed in a timely manner to conclude within the Salesforce timeout limit and within user expectations.
      Data Volumes

      This pattern is used primarily for small volume, real-time activities, due to the small timeout values and maximum size of the request or response for the Apex call solution. Do not use this pattern in batch processing activities in which the data payload is contained in the message.

      Remote Process Invocation—Fire and Forget

      This pattern is utilized when you want to send some information to remote system and don’t want wait for response. Consider the scenario in which order is created in salesforce and then order information is send to order fulfillment system (outside salesforce) which will process the order.
      Best example for this pattern utilization is Outbound messages.

      Different Scenarios:
      • Outbound messages and call back
      This is best use case for this pattern as information will be send from salesforce using outbound message without any customization. If other system is unavailable then, outbound has in-built retry mechanism for 24 hours.
      Also we can pass session id of user so that remote system can perform callback to SFDC to update records providing confirmation that request have been successfully received by remote system.
      Given the static, declarative nature of the outbound message, no complex integration such as aggregation, orchestration, or transformation, can be performed in Salesforce. The remotesystem or middleware must handle these types of operations .
      • VF and custom controllers
      You can utilize VF page and controllers to send information to remote system but it involves customization to grantee delivery of messages as remote system can be have downtime when request is send.
      • Apex triggers/Batch Class
      You can use Apex triggers to perform callouts based on record data changes. All calls made from within the trigger context must execute asynchronously from the initiating event. Batch and triggers also have API call limits

      Error Handling and Recovery

      An error handling and recovery strategy must be considered as part of the overall solution. The best method depends on the solution you choose.
      • Apex Callout – We need to maintain logic for retry and error handling if we didn’t get acknowledgement from remote or gets timeout error. Recovery mechanism is complex in this scenario
      • Outbound messages – Outbound has inbuilt retry mechanism.

      Security Considerations

      A call to a remote system must maintain the confidentiality, integrity, and availability of the request.For Outbound message, Whitelist Salesforce server IP ranges for remote integration servers as all Outbound messages are delivered from Salesforce IP addresses.


      Timeliness is less of a factor with the fire-and-forget pattern. Control is handed back to the client either immediately or after positive acknowledgment of a successful hand-off in the remote system. With Salesforce outbound messaging, the acknowledgment must occur within 24 hours; otherwise, the message expires.

      Data Volumes

      Data volume considerations depend on which solution you choose. There is no limit on number of outbound messages sent but limits are there for apex callouts.

      Note:- I have summarized the information provided in Integration Patterns and Practices documentation provided by salesforce in this blog.

      Hope this will help!!!

      Thursday, November 15, 2018

      Lightning Treegrid : Generic Component to display hierarchy in tabular format for any sobject

      In this blog, I am going to share a reusable component which can be used to display hierarchy of records along with other fields information in treegrid format.

      Previously we have to use jquery to implement this but now "Lightning:treegrid" tag have been introduced which can be used to display treegrid in lightning framework.

      In order to use this component, you have to pass below parameters to this components:
      • ltngcurrentRecId =  RecordId (15 or 18 digit)
      • ltngSobjectName = Object API Name
      • ltngParentFieldAPIName = Parent Field API name which create self relationship
      • ltngColumnLabelList = Specify the column label
      • ltngColumnAPINameList = Specify the API field names in same order as that of column
      • ltngHyperlinkColumn = Field API Name which will work as hyperlink for record detail page
      Suppose you have display treegrid for Account hierarchy by using below syntax:

      <c:SK_GenericTreeGridCmp ltngcurrentRecId="0019000000ld4kS"
      ltngColumnLabelList="['Name','Type','Industry','Account Owner']"

      Below is output:

      Suppose you have to display case hierarchy, then use below code snippet:

      <c:SK_GenericTreeGridCmp ltngcurrentRecId="5009000000GJkJE"
      ltngColumnLabelList="['CaseNumber','Subject','Status','Case Owner']"
      ltngHeaderValue="Case Hierarchy"/>

      Below is output snapshot

      Below is complete code snippet for your reference:

      You can download the code from GitHub by using below URL:


      • Specify Field API properly as javascript is case sensitive. For example, specify "Name" instead of "name"
      • For adding parent field API names, provide API names properly. For example for Account owner use, "Owner.Name" instead of "".
      Hope this will help!!!

      Saturday, November 10, 2018

      Lightning Components Tutorial : Easy way to become Lightning developer

      In this blog, I am going to share all lightning components concept which is required for Lightning developer starting from basics to advance topics.

      You can learn lightning in 25 days by following below 25 blogs related to lightning.
      1. Lightning Component Basics: Lightning Component Framework
      2. Lightning Components Basics : Attributes, Expressions and Value Providers
      3. Lightning Components Basics : Handling Actions in Controller.js
      4. Lightning Components Basics : Considerations while calling server-side controller actions
      5. Application Events : Way to Communicate Between Different Lightning Components
      6. Component Events: Way to Communicate Between Components in Containment Hierarchy
      7. Raising and Handling Custom Events in Salesforce Lightning
      8. Salesforce Lightning Events : Hands on Training Guide
      9. Salesforce 1 Events in Lightning Experience and Salesforce 1 app
      10. Lightning Data Services : Way to perform operation on records without using server-side Apex class
      11. Lightning Data Services : Hands on Training Guide
      12. Creating Lightning Components Dynamically
      13. Dynamically Creating and Destroying Lightning Button(ui:button)
      14. Adding Lightning Components in VF Page and Passing Values from URL
      15. Inheritance in Lightning Components
      16. Firing Event from Lightning Component and Passing Parameter to VF Page
      17. How to Fire Lightning Events from VF Page in Lightning
      18. Custom Component to show Loading Spinner in Lightning during Server or Client side Operations
      19. Why to use design resource in Lightning bundle and how to add dynamic Options in datasource for Design Component
      20. Formatting and Localizing dates in javascript in Lightning
      21. Using Chartjs in Lightning Components
      22. Lightning Tree : Generic Lightning Component to Display Hierarchy for any sObject
      23. Lightning:treegrid - Displaying Account hierarchy using treegrid
      24. Aura.Action : Lightning Framework Specific Attributes Type
      25. Aura.Component[] : Lightning Framework Specific Attributes Type

      Hope this will help!!

      Tuesday, November 6, 2018

      Aura.Action : Lightning Framework Specific Attributes Type

      In this blog, I am going to explain "Aura.Action" attribute type and its usage.

      There is another Lightning Framework specific attribute "Aura.Component[]". If you want to learn more about this then refer below blog:

      Aura.Component[] : Lightning Framework Specific Attributes Type


      Use this type of attribute if you want to pass the reference of parent lightning component controller.js function to nested/child lightning component. This will help to invoke parent component JS function from child component markup.

      Below is syntax to define this kind of attribute:

      <aura:attribute name="parentJSFunction" type="Aura.Action"/>

      This is useful if you want to make reusable component to appear based on values passed from parent and close/hide the component by invoking parent lightning component JS function.

      I have created a sample component to explain how to invoke parent component function and child component function by passing "Aura.Action" attribute to child component.

      Below is snapshot of Lightning component ("SK_AuraActionDemoCmp")  UI which contains child component ("SK_AuraActionChildCmp")  inside it.

      Child component contains 2 buttons which will invoke JS function of parent and same component. Child component contains an attribute of type "Aura.Action" through which we will parent parent component JS function reference.

      <aura:attribute name="closeChildDivFunction" type="Aura.Action" default="{!c.defaultCloseAction}"/>

      If you don't pass JS function from parent component then child component will invoke its own JS function "defaultCloseAction".

      If user click on these 2 buttons, then below things will happen:

      • If user clicks on "Close via Parent JS function" button,then complete content will also get removed and ltnguserActionMessage will display message saying "Close via Parent JS function button clicked. Please refresh your browser if you again want to load this demo component"

      • If user clicks on "Close via ChildCmp JS function" button,then only child component body will be removed and ltnguserActionMessage  will display message saying "Close via ChildCmp JS function button clicked.Please refresh your browser if you again want to load this demo component"

      Please find below complete code reference:

      Hope this will help!!

      Thursday, November 1, 2018

      Lightning:treegrid - Displaying Account hierarchy using treegrid

      Salesforce has introduced new tag called lightning:treegrid which can be used to display tree structure in tabular form. Lightning:tree can be used to display the hierarchy but if you want to display additional information then lightning:treegrid becomes useful.

      If you want to lean how to use lightning:tree tag to display hierarchy for any record then refer below URL:

      Lightning Tree : Generic Lightning Component to Display Hierarchy for any sObject

      If you have to display account hierarchy along with another fields information as displayed in below image, then use treegrid.

      Below is complete code to display account hierarchy. Just pass account record Id and lightning component will display complete hierarchy.

      Hope this help!!!

      Tuesday, October 30, 2018

      Aura.Component[] : Lightning Framework Specific Attributes Type

      We know that there are different attribute types supported for attribute in lightning like Boolean, date, datetime, decimal, double, integer, long, string, collections (list,set,map), sobjects, user defined data types(wrapper class) etc.

      Below are 2 different types which are supported as attribute type and specific to lightning framework:
      • Aura.Component[]
      • Aura.Action
      In this blog, we are going cover all aspect of Aura.Component[] attribute type. If you are interested in learning more about Aura.Action, then refer below blog:

      Aura.Action : Lightning Framework Specific Attributes Type


      An attribute of this type is considered as facet. You can use this in order to set markup to use it in multiple places.
      You can consider it some what similar to defining templates with <apex:composition> in VF pages.

      To set a default value for "Aura.Component[]", specify the default markup in the body of aura:attribute. For example:

      <aura:attribute name="MarkupDetail" type="Aura.Component[]">
      <p>Aura.Component[] default value</p>

      So when this facet attribute(MarkupDetail) value is not set in component, then this default mark up will apear.

          <c:aurafacet >        
              <!--we are not setting MarkupDetail attribute value so this will display 
      default body specified in MarkupDetail attribute--> 

      Output will be:

      Aura.Component[] default value

      Below is sample code which include different components and usage of Aura.Component[] in it. Also it will explain how to reuse the component body.

      Below is output snapshot:

      Points to be noted:

      • When we didn't set the attribute value of type Aura.Component[], then it display default body specified within Aura.Component[].
      • When we set attribute value of type Aura.Component[], component will render based on given values.
      • Different div are being getting created with different content in that.

      Hope this helps!!!

      Monday, October 29, 2018

      Way to get complete RecordType Information (like DeveloperName) using describe

      In summer'18 release, new methods have been introduced through which we can retrieve all recordtype info using describe information. Below are 2 methods introduced in summer'18:

      • Schema.DescribeSObjectResult.getRecordTypeInfosByDeveloperName()
      • Schema.RecordTypeInfo.getDeveloperName()

      Suppose you want to retrieve all recordtype information for account object then use below code:

      Below is console output

      Hope this help!!

      Thursday, October 4, 2018

      Lightning Component Basics: Lightning Component Framework

      In this blog, I am going to provide basic overview of lightning component framework.

      Lightning component framework is being referred as MVCC modal.

      • Modal
      • View
      • Client-Side Controller
      • Server-Side Controller
      In lightning components, Lightning bundle which contains component markup, controller.js (client-side), helper.js (for utility or reusable code) etc acts as primary interface and from client side controller, we can perform server side calls(apex class method invocations).

      All calls from Lightning components to server are asynchronous call and we capture the response using callback function.

      Below diagram will help you to understand Lightning component framework:

      Hope this will help!!!

      More Blogs:

      Saturday, September 29, 2018

      Lightning Components Basics : Considerations while calling server-side controller actions

      In this blog, we will cover how to call apex class method from Lightning component and different considerations that we need to consider while performing server side call. Actually all calls to server for apex class routed through controller.js function. From lightning component, you can call controller.js function from where you can call apex method.

      First of all in order to associate an apex class with lightning component, you have to specify apex class name in controller attribute.

      Also remember that all apex methods or apex member variables needs to annotated with @AuraEnabled.

      Below is sample apex class which will be called from lightning:

      public class SK_LightningBasicsSSController {
          public static List<Account> findRecentAccounts(){
              return [select id,name,type from Account 
                      order by LastmodifiedDate DESC Limit 10];

      In order to associated this class with lightning component, use below syntax:

      <aura:component controller="SK_LightningBasicsSSController">
          <!-- you code-->

      Now we will call apex method on load of lightning component and will display returned list of accounts.

      Below is process to call apex method from controller.js

      //Create instance of apex method by using c. annotation followed by method name.
      var actionName= component.get("c.findRecentAccounts");
      //Specify the callback function as all calls are asynchronous. this callback will be invoked once //response is returned by apex class
      actionName.setCallback(this, function(response) {
      var state = response.getState();
       //Check response state for SUCCESS and ERROR
      if (state === "SUCCESS") {
        //store the response in variable
      var apexResponse=response.getReturnValue();
                      //set response to attribute value
      }else if(state === "ERROR"){
      var errors = response.getError();
      alert('Problem with connection. Contact your system administrator.');
      //do not forget to add below line as this put this request in queue for asynchronous call

      Below is complete code snippet:

      Important Points to remember:

      How to call apex method which contains parameters

      If you have method defined with some parameter, for example search string to search account as mentioned below:

      Public static List<Account> SearchAccounts(string searchString){
             //your logic

      So in order to pass parameters to apex class method, create a JSON as mentioned below:
      Suppose you have an attribute defined to take input from user say AccName:

      <aura:attribute name="AccName" type="string"/>

      var actionName= component.get("c.SearchAccounts");
      var params = {
                               "searchString" :component.get("v.AccName")

      • While creating JSON for parameters, key Value should be similar to parameter name in apex method. In our case the apex method parameter name was "searchString" so while creating JSON we specified first key Value as "searchString".
      • If you have multiple parameters, then create JSON as mention below:
                var params ={
                                       "param1":"param value1",
                                       "param2": "param value2",
                                       "param3": "param value3"

      Create helper function which can be reused for different apex method calls

      Instead of writing same piece of code to call different apex methods, we can write function in helper.js which can be invoked from controller.js function by passing the parameters to it.

      I have created a helper function which takes 4 parameters:
      • Component reference
      • apex class method name
      • callback function name
      • param (to specify parameters if apex method expect some parameters or arguments)
      Below is helper function "callToServer"

      callToServer : function(component, method, callback, params) {
              var action = component.get(method);
              console.log('****param to controller:'+JSON.stringify(params));
              action.setCallback(this, function(response) {
                  var state = response.getState();
                  if (state === "SUCCESS") {
                  }else if(state === "ERROR"){
                      var errors = response.getError();
                      alert('Problem with connection.'+errors);

      Now if you have to call apex class method from controller.js then use below syntax:

          doInit : function(component, event, helper) {
              var params = {
                                       "searchString" :component.get("v.AccName")
                      console.log('apex response :'+JSON.stringify(response));

      How to call different apex methods in sequential order

      All calls to apex methods are asynchronous so if there is need to first call a apex method and based on response call another apex method, then you need to make sure that you perform second call to server after getting the response from first function.
      So always perform second call to server from inside the callback function which get invoked when asynchronous call finished on server. 

      If you use helper function approach to call apex methods then you can use below syntax to call 2 different (searchAccounts and findAccountdetailsapex method in sequential order.

      var param1= {
                               "searchString" :component.get("v.AccName")
      var selectedId = response[0].id;
      var param2 = {
      "ltngAccId": selectedId
      //creating component dynamically using helper function
         //your logic

      Use Wrapper to get all data in single call

      Avoid multiple calls to server in order to fetch information as it will degrade the performance.
      Use wrapper (user defined data types) to return complete information in single server call.

      Hope this will help!!!

      Friday, September 28, 2018

      Lightning Components Basics : Handling Actions in Controller.js

      Lightning component bundle comes with different resources like controller.js, helper.js, style.css etc.

      All the actions performed on lightning component, can be handled in controller.js.
      helper.js worked as an utility which can be called multiple times. If you want to call same piece of code multiple times, then specify it as separate reusable function in helper.js and call it from controller.

      I have created a sample lightning component "SK_LightningBasics". Below is code for that:


      <aura:component >
          <aura:attribute name="ltngFirstname" type="string" default="Sunil"/>
          <aura:attribute name="ltngLastname" type="string" default="Kumar"/>
          <!--Mark up starts-->
          <lightning:input aura:id="userFn" value="{!v.ltngFirstname}" name="ufn" label="Firstname"/>
          <lightning:input aura:id="userLn" value="{!v.ltngLastname}" name="uiln" label="Lastname"/>
          <lightning:input aura:id="useremail" value="" name="uinput" label="Enter Email"/>
          <lightning:button name="btn" label="Display" onclick="{!c.displayMessage}"/>
          <!--Mark up ends-->


      displayMessage : function(component, event, helper) {
                   var fname= component.get("v.ltngFirstname");
                   var lname= component.get("v.ltngLastname");
                   //how to get input by user 
                   //which is not related to attribute
                   var emailInputTag= component.find("useremail");
                   //Now you can refer any attribute on input tag
                  var emailvalue= emailInputTag.get("v.value");
                  //to find label for email input
                  var emailLabel= emailInputTag.get("v.label");
                  var alertMsg='displayMessage function get called.\n';
                 alertMsg = alertMsg +'Email entered is -'+emailvalue;

      Lightning is based on MVCC (Modal-View-Client side controller-Server side controller), so first functions defined in controller.js is called first and then if needed we can call server side apex class methods.

      In above lightning components, we are using onclick attribute on lightning button which invokes controller.js function.

      In lightning, we refer controller.js functions using c.annotation inside "{! and }".
      For example{!c.displayMessage}

      Way to invoke controller.js function when component loaded initially

      Lightning framework provide standard events which can be used to invoke controller.js function.
      Use below syntax to invoke controller.js function when component is getting loaded:

      <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

      Specify the controller.js function which you want to invoke. By using above code snippet, we are calling doInit function in controller.js.

      doInit: function(component, event, helper) {
                   alert(' doInit get called');
            displayMessage : function(component, event, helper) {
                   //your logic

      Way to invoke controller.js function when any attribute value gets changed

      Use change event on attribute to invoke controller.js function.

      Sample code snippet:

      <aura:attribute name="ltngFn" type="string" default="Sunil"/>
      <aura:handler name="change" value="{!v.ltngFn}" action="{!c.OnChangeFunction}"/>

      So whenever "ltngFn" attribute value will be changed then, OnChangeFunction will be invoked

      doInit: function(component, event, helper) {
                   alert(' doInit get called');
            displayMessage : function(component, event, helper) {
                   //your logic
            OnChangeFunction: function(component, event, helper) {
                   alert(' Attribute value gets changed');

      In order to test these component code, you can either create lightning tab or create lightning app and preview it. Below is code for lightning app:

      <aura:application extends="force:slds">


      After creating this app, click on preview button on top right side in developer console.

      Hope this will help!!

      Saturday, September 22, 2018

      Lightning Components Basics : Attributes, Expressions and Value Providers

      Attributes are just like apex class member variables which holds some value and can be used in performing any operation.
      Same like apex class member variable, you need to define name of attribute, datatype of attribute and you can also define default value which is optional.
      Below is syntax to define attribute:

              <aura:attribute name="firstname" type="string" default="Sunil"/>

      Other attributes are:
      • access- Indicates whether the attribute can be used outside of its own namespace. Possible values are public (default), and global, and private.
      • required - If it is required to specify the value of attribute. The default is false.
      • description - Specify the purpose and usuage of attribute.
      Supported values for type are Boolean, date, datetime, decimal, double, integer, long, string, collections (list,set,map), standard and custom objects and user defined data types(wrapper class).

      Please refer below URL for more information on basic data types:

      Component Attributes Types
      Salesforce recommend using type="Map" instead of type="Object" to avoid some deserialization issues on the server. For example, when an attribute of type="Object" is serialized to the server, everything is converted to a string. Deep expressions, such as can throw an exception when they are evaluated as a string on the server. Using type="Map" avoids
      these exceptions for deep expressions, and other deserialization issues.

      Checking for Types
      To determine a variable type, use "typeof" or a standard JavaScript method instead. The "instanceof" operator is unreliable due to the potential presence of multiple windows or frames.


      Expression are kind of formula which can be used within expression delimiters (“{!” and “}”)in expressions, you can specify attributes or different operators to give you output.

                <aura:attribute name="msg" type="String"/>  
                  <p>{!'Hello! ' + v.msg}</p>

      Value Providers

      Value providers helps you to access attributes values and you can use them either in component markup or in JavaScript functions. Using value providers, you can either set or get attributes values.

              <aura:attribute name="msg" type="String"/>  
                  <p>{!'Hello! ' + v.msg}</p>

      • Way to find attribute value in controller.js:

                     var msgValue = component.get("v.msg")

      • How to set attribute value in controller.js

                    component.set("v.msg","Sunil Kumar");

      Friday, September 14, 2018

      Lightning Component For Timer

      I have created a lightning component to display timer. This is useful when you want to display timer to end user so that he/she can understand remaining time.

      This component can be used if you are planning to create time tracking app or online exam screen.

      Below is complete code snapshot:

      Hope this will help!!

      Lightning Component for Stopwatch

      I have created a lightning component which can work as stopwatch and will display time in "hh:mm:ss" format.

      Below is complete code for this lightning component:

      Hope this will help!!

      Monday, September 3, 2018

      lightning:isUrlAddressable Interface: Way to get URL parameters in Lightning Components

      In Summer'18 release, Salesforce introduces new interface for lightning components which can be used to fetch URL parameters in lightning components.

      Before this, we have to write logic in controller.js function to get current URL and split the url parameters.

      If we are using lightning tab and displaying lightning component, then we can fetch URL param by using "{!v.PageReference.state.xxxxx}" where xxxxx is URL parameter name.

      I have created a lightning component "SK_URLParamCmp.cmp" in order to explain the usage of this interface. Below is code snapshot:

      Now I have created a lightning tab "SK_URLParam_Tab", which will open this lightning component.  Pass any value in URL as "accname" as parameter. Below is sample URL:


      Below is UI snapshot:

      Hope this will help!!


      If changes to lightning Components are not reflecting immediately in lightning tabs, then you have to disable the "Enable secure and persistent browser caching to improve performance" option under Caching section in Session settings.

      For more details on this setting, please refer below URL:
      Improved Performance with Secure Client-Side Caching

      Friday, August 24, 2018

      Way to get list of Scheduled reports and Jobs from Salesforce

      This is very common ask from business admins or end users to get list of schedule reports or schedule jobs (batch jobs, scheduled jobs etc) from Salesforce.

      There is no standard view provided by Salesforce to view list of scheduled reports or reports. Users have to navigate to Monitor section under SetUp.

      This section display list of jobs either schedule or completed jobs but does not provide complete list of jobs.

      By using apex, you get the list of schedule reports or jobs in csv format via email. 

      Please find below the apex code for that:

      Now if you have to get list of scheduled reports in your org, then just execute below script in developer console:

      • For getting list of scheduled reports:         SK_ScheduleJobUtility.findScheduledJobDetails('Report Run');

      • For getting list of scheduled batch jobs:         SK_ScheduleJobUtility.findScheduledJobDetails('Batch Job');

      • For getting list of scheduled apex jobs:        SK_ScheduleJobUtility.findScheduledJobDetails('Scheduled Apex');

      Important Use case

      Sometime reports are scheduled by user which becomes inactive, then all system admin start getting email saying:

      "The user account that runs the report (the running user) is inactive."

      This utility will send email along with user details which will help in identifying all inactive user for whom reports are scheduled as running user.

      Hope this will help!!

      Looking forward for everyone's comments and feedback.

      Monday, August 20, 2018

      Creating Lightning Components Dynamically

      Through this blog, I will share the approach to create lightning components dynamically by sharing an example in which we will display account summary information by creating summary component dynamically.

      I have already posted one blog through which we can create ui:button dynamically and can destroy it. Please refer below URL if you want to refer that before continuing with this blog:

      creating or destroying buttons dynamically

      Below is snapshot of app which will display recent accounts on left side and on right side, it will display opportunities and case summary for account. You can click on "show Info" link before any account record and its related information will appear on right side dynamically.

      Code to create dynamic component

      You can use $A.createComponent method which accepts 3 parameters:
      1. ComponentName (String) :Type of component to create like "c:newCmp" etc.
      2. attributes : JSON specify component attributes values
      3. callback function: Once the component is created, this callback function will be invoked.This function can be used to append newly created component to target component. You can place the newly created component inside some div to display.
      Below is sample code along with comments to explain steps:

       //find the div markup where you want to display dynamic component
      //here "dynamicCmpSection" is aura:id of div
      var targetCmp = component.find("dynamicCmpSection");
      //create JSON specify all attributes needed for new component
      var cmpAttributes = {
                      "attribute1": "attribute Value",
      "attribute1": "attribute Value"
      function(tempbody) {
      //Check if component is valid
      if (component.isValid()) {
      var targetCmp = component.find("dynamicCmpSection");
      //first remove all content inside the div by making its body as null
      var body = targetCmp.get("v.body");
      //add newly created component in div
      targetCmp.set("v.body", body);
      console.log('***component loaded successfully');

      Below is complete code related to snapshot shown in blog.

      Hope this Helps!!

      Sunday, August 19, 2018

      Application Events : Way to Communicate Between Different Lightning Components

      Application events are used to communicate between different lightning components. These are different from component events as these are not dependent on containment hierarchy.

      Application events behaves similar to standard events. There is no need to register for application event by any component. Any component can fire application event where as in component events, components have to register first in order to fire that event.

      If you want to learn more about component events, then refer below URL:
      Component Events: Way to Communicate Between Components in Containment Hierarchy

      Through this blog, I will explain different aspect of using application events:

      I have created a lightning app which contains 2 separate components. User is entering some information and sending it to second component by clicking on button.

      Below are different steps you need to follow in order to implement application events:

      • Create lightning event "SK_MessagerEvent" of type Application
             <aura:event type="APPLICATION" description="Event template" >    
                  <aura:attribute name="msg" type="String" access="GLOBAL"/>                           

      • Use below syntax to fire event from lightning component:
              var appEvent = $A.get("e.c:SK_MessengerEvent");

      • Create handler in component which want to consume or catch the information passed using application events.
             <aura:handler action="{!c.handleNotification}" event="c:SK_MessengerEvent" />
      • Create function in controller.js which will get invoked whenever this application event will be fired.
              var sentMessage= event.getParam("msg"); 
              console.log('******sentMessage by app event:'+sentMessage);

      Below is complete code for your reference related to snapshot shown above:

      Hope this help!!

      More Blogs>>: 
      COMPONENT EVENTS: Communicate Between Components in Containment Hierarchy    

      Monday, August 13, 2018

      Component Events: Way to Communicate Between Components in Containment Hierarchy

      Components events can be used to pass information between lightning components which are in containment hierarchy. Component events can be handled by component which is firing it or by component container.

      If you want to learn more about Application events, then refer below URL:
      Application Events : Way to Communicate Between Different Lightning Components

      Through this blog, I am going to explain how to utilize component events with sample code.

      I have created a sample lightning app which contains "c:SK_MasterCmp".  "c:SK_MasterCmp" contains another component "c:SK_ChildCmp"

      Below are steps which you need to follow while utilizing component events:

      • Create Lightning event of type "COMPONENT".
              <aura:event type="COMPONENT" description="Event template" >
                    <aura:attribute name="passedValue" type="string"/>

      • Register the component event which is going to fire component event.
              <aura:registerEvent name="changeValueEvent" type="c:SK_LightningEventChannel"/>
      • Use below syntax to fire event and pass information from "c:ChildCmp".
              var newEvent = component.getEvent("changeValueEvent"); 
              newEvent.setParams({"passedValue":"twitter handle-@sunil02kumar"});                               
      • Create handler in component which needs to handle the events means want to consume that information. Note the name of handler should be same as that while registering event:
             <!--name should be equal to name while register event-->
             <aura:handler name="changeValueEvent" event="c:SK_LightningEventChannel" 
      • Create function in controller.js which will be called when "c:MasterCmp" will handle the the event.
             handleNotification : function(component, event, helper){
                 console.log('****handling event');
                 var sentMessage= event.getParam("passedValue");
                 component.set("v.mastervalue", sentMessage);

      Below is complete code for reference:

      Hope this help!!