Extract nested attribute value from JSON String using Apex

Salesforce offers two main ways to extract values from a JSON string
1) JSON.deserialize() This approach requires you to have a wrapper class/other valid entity to deserialize the data to.
2) JSON.createParser(jsonString) This approach requires you to loop through a bunch of confusing parser.nextToken() calls

In this article I am introducing an easy to use utility to extract inner attribute values from any JSON string. This is leveraging JSON.createParser(). But once you have this utility, you don't have to go through the parser.nextToken() confusion.

Example of use
Utils.extractAttributeFromJson('{"data":{"user":{"organization":{"id":"123"}}}}', 'data.user.organization.id');


Please note that it will be more performant to use JSON.createParser() directly if you have multiple attributes to extract from the JSON.

How to schedule a class to run once at a specific time from apex

Salesforce gives out of the box ability to schedule apex classes with some limited options to control frequency under setup => apex classes => "Schedule Apex" button. But this approach limits you to run apex classes only at the start of the hour.

If you have a need to run a scheduled apex class at a specific time, you can use custom CRON expressions gives a more flexible way to do that.


Note that nextRun can be any datetime value in this case. Here we generate a cron expression from the datetime provided. If you want to read more about cron expressions refer this blog.

How to scan barcode values and send to Salesforce

Here we are covering how we can scan barcode values and execute some actions in Salesforce using the scanned data. This is achieved using a mobile app "Barcode To Cloud". It is available for iOS and Android as FREE to get started.

This app allows you to scan different barcode formats (QR Code, Code 128, Code 39, Data Matrix, Codebar, PDF417, EAN13, ISBN etc) and send data to Salesforce. You can configure the app to do differnt activities in Salesforce when a barcode or QR code is scanned.

Below actions can be configured in the app using the data obtained from scanning.

  • Create a record in Salesforce with data from barcode
  • Find a record in Salesforce matching barcode data and display in the app
  • Find a record with barcode data and update it
  • Find a record with barcode data and delete it
  • For complex operations including records from multiple objects, create a record in Salesforce using barcode data and use a trigger/process builder to execute additional operations


Short Demo Video

Full Demo Video

This video shows a detailed walkthrough of the app covering below items.

  1. Connecting to Salesforce - watch
  2. Receive shipments at warehouse with notes - watch
  3. Receive shipment and scan continuously - watch
  4. Importing configuration - watch
  5. Retrieve account details when account number barcode is scanned and allow users to update details - watch
  6. Track attendance at an event using barcode in ticket - watch
  7. Simple demo - Post scanned barcode to chatter as the scanning user - watch


Demo Video (Old Version)

This video shows a detailed walkthrough of the app covering below items.

1) Connecting to Salesforce

2) Updating Checked In At field on lead record when lead's email is scanned using the app

3) Displaying lead record details by scanning email QR code

If you are looking for a free appexchange app to generate barcode, please check out Barcode and QR Code Generator.


Use cases

Barcode generation and scanning can be used to improve a lot of business processes. Some examples are,

  • Generate product barcodes and stick it as labels to products so that you can scan using mobile app and add products to opportunity
  • Generate QR code corresponding to your event registration custom object field(Id or registration number). Send QR code in email confirmation to the users. Later when users arrive at the event you can scan reservations using the mobile app
  • Stick a QR code in your outgoing shipments and incoming shipments. Then scan it and send to Salesforce records using the mobile app so that you can track shipments at different stages of shipping

Export/Import Configuration

This configuration driven app allows you to export the configurations you created and share with your team members. Your team members can later import these configurations and the app will be ready to use without any additional configuration


Need fully branded mobile app for your business?

This is a generic mobile app designed to support use cases of all types of users. So features in the app are generic. If you need a fully custom branded mobile app that interacts with your Salesforce environment and designed spcifically for your business requirements, please contact me at albertsfo1@gmail.com

Display barcode in Salesforce record detail view as a button

Here we cover an easy way to display QR code in Salesforce classic using a free appexchange app Barcode and QR Code Generator.

This app allows you to generate barcode in Salesforce without depending on any external services. In below step by step guide, we are assuming that you have installed the app already. If not please go to Barcode and QR Code Generator and install.


Example - Displaying QR code using custom field in custom object

Here we will go through an example of displaying QR code using data from a custom field. Here for demo purpose I have created a custom object with name Demo_Record__c. This object has a custom field with API name Unique_Field__c. This is just one example. Same approach will work for any other field in any custom/standard object in Salesforce.


1) Create a barcode config record for the custom object and field combination

Go to "Barcode Configs" tab that comes with the app and create a new record. Give it a name without spaces or special characters. I am giving it a name DemoUniqueFieldConfig. Specify Demo_Record__c as object name and Unique_Field__c as field name. Then in order to display QR code, I am selecting "QR Code" from "Barcode type" picklist/dropdown field. You can leave other fields with default values. Then save the record. Please check below screenshot,

2) Create a custom button to display QR Code in "Demo Record" page layout

Navigate to "Setup => Objects => Demo Record". Scroll down to "Buttons, Links, and Actions" section and create a new button.

Generally to display barcode in a new widow you can just redirect user to below URL pattern /apex/BarQR__BarcodeGeneratorPage?configName=YOUR_CONFIG_RECORD_NAME_HERE&recordId=RECORD_ID_HERE

We are doing the same here in the button. We are using the configuration record name DemoUniqueFieldConfig from Step 1 and passing recordId dynamically using {!Demo_Record__c.Id}.

Save your button code. At the end you can add the button to page layout under "Setup => Objects => Demo Record => Page Layouts => Edit". Check below screenshot.

Click save and navigate to a record details page. You will be able to see "QR Code" button in the page. When you click on the button, QR code will be displayed in a popup window using data from the field you configured.

Result

Example from Salesforce classic view.

Since our "QR Code" button is a custom button that redirects the user to a page with barcode, it will be available in lightning experience also. But in lightning Barcode/QR code will be more easily accessible if you add it through app builder page. Checkout example of adding barcode component directly in lightning app builder page


Use cases

Barcode generation and scanning can be used to improve a lot of business processes. Some examples are,

  • Generate product barcodes and stick labels to products so that you can scan and add products to opportunity
  • Generate QR code corresponding to your event registration custom object field(Id or registration number) and email users, so that you can scan in participants at the time of the event
  • Stick a QR code in your outgoing shipments and incoming shipments and then scan it into Salesforce records so that you can track shippings end to end

Displaying barcode in Salesforce lightning experience natively

Here we cover an easy way to display barcode in lightning experience using a free appexchange app Barcode and QR Code Generator.

This app allows you to generate barcode in Salesforce without depending on any external services. In below example, we are assuming that you have the app installed already. If not please go to Barcode and QR Code Generator and install.


Example - Displaying barcode using email field in lead

Here we will go through an example of displaying barcode using data from email field in lead records. This is just one example. Same approach will work for any other field in any custom/standard object in Salesforce.


1) Create a barcode config record for lead email field

Go to "Barcode Configs" tab that comes with the app and create a new record. Give it a name without spaces or special characters. Specify lead as object name and email as field name. You can leave other fields with default values. Then save the record. Please check below screenshot,

2) Add Barcode component to lead flexipage and activate

Once you have created a barcode config record, it is just matter of editing lead flexipage and adding "Barcode and QR Code Generator" component to the page.

First go to a lead record details page. Click Gear Icon and "Edit Page".

Drop "Barcode and QR Code Generator" component from left sidebar to the place you need. It will ask for a configName. Give the name of the record you created from step 1.

Click "Save" button on top right and finally click "Activation" on top right and assign the page as organization default (or based on your app or profile preferences).


Result

If you followed the steps correctly, you should see barcode when you go to any lead record page.


Use cases

Barcode generation and scanning can be used to improve a lot of business processes. Some examples are,

  • Generate product barcodes and stick labels to products so that you can scan and add products to opportunity
  • Generate QR code corresponding to your event registration custom object field(Id or registration number) and email users, so that you can scan in participants at the time of the event
  • Stick a QR code in your outgoing shipments and incoming shipments and then scan it into Salesforce records so that you can track shippings end to end
  • Need to scan the barcode values to Salesforce as well? Check out the article here

Long-Running callout with continuation in Lightning

API callouts that take more than 5 seconds are called long-running callouts. Salesforce allows only 10 long-running callouts at a time in an environment. To avoid hitting this limit Salesforce provides continuation. This uses a callback mechanism and can be implemented in Visualforce or Aura.

Use cases

If you have an integration that is used by more than 10 concurrent users and the API can take more than 5 seconds to respond, you should consider using continuation.

Steps to Implement

STEP 1 :- Create a remote site setting/named credential corresponding to the API you want to access. You can find remote site settings under setup => remote site settings. To follow this example, create a remote site setting whitelisting the domain https://salesforcecodes.blogspot.com/

STEP 2 :- Create an apex class that has an AuraEnabled method and annotated as continuation=true. This method starts the continuation processing. Add a second method to process the result. It is processBlogResponse in our example.


STEP 3 :- Create an aura component and call the apex method annotated with continuation=true. Syntax to call continuation method from aura is similar to calling other apex methods from aura.


STEP 4 :- Create an aura app or flexi page to display your aura component with continuation. In this example I am creating a TestApp aura applicaiton. After this go to https://YOURDOMAINHERE.com/c/TestApp.app to see the application displaying blogs retrieved using continuation.


How to authenticate to Salesforce APIs without client Id and secret

There are multiple ways to authenticate to Salesforce SOAP and REST APIs. Usually the recommended way is to authenticate to REST API is by using OAuth and creating a connected app in Salesforce. Please check the article Using curl to authenticate to Salesforce REST API to see an example.

There is an easy way to bypass OAuth and directly use username+password combination to authenticate against Salesforce SOAP and REST APIs. It is by making SOAP login call. It will return an session Id that you can use against Salesforce SOAP and REST APIs as access token.

Getting access token with username, password and security token

You need make a HTTP call using below format. This is basically sending a login SOAP request. Make sure to use your username, password and security token in line 12 and 13. Also if you are accessing a Salesforce sandbox base part of the URL changes to https://test.salesforce.com

You can see that the API response contains sessionId tag. You can use this sessionId to call Salesforce SOAP or REST apis. Checkout below example of accessing Salesforce Rest API with the session Id. Make sure to use your session ID in authorization header and your base endpoint instead of https://salesforcecodestest-dev-ed.my.salesforce.com.

This method allows you to access Salesforce REST and SOAP apis without a client ID and secret. This is intended for server to server communication. If you use it in a client side app, you will see CORS errors.

Retrieving metadata from Salesforce using package.xml and SFDX CLI

Salesforce ecosystem provides a number of tools to retrieve metadata from connected Salesforce environment. There is an option in Salesforce extension pack for vscode to pull metdata from your connected Salesforce environment. But sometimes you still need to pull metadata from unreleated environments for purposes like committing to a git repository or deploying.

Metadata type names can be tricky and it usually difficult to create a package.xml without some googling. Please checkout article on How to create package.xml in Salesforce - With Samples

Retrieving metadata using package.xml

Once you have package.xml, you are only couple of commands away from retrieving metadata with it. Please follow below steps,

  1. Make sure you have SFDX CLI tool installed. If not download and install it from SFDX CLI Downlaod
  2. Make sure your CLI is connected to the environment from where you need to retrieve metadata. If not use below command to authenticate your Salesforce environment

    sfdx force:auth:web:login -r "https://yourSalesforceEnvironmentUrlHere.com" -a aliasNameHere

  3. Copy package.xml to your command line location and create a folder with name "metadata" to store the metadata and run below command

    sfdx force:mdapi:retrieve -r metadata -k ./package.xml -w 5 -u aliasNameHere

You will be able to see a progress status and SFDX should retrieve code and put in your metadata folder as a zip file


Package.xml samples to retrieve Salesforce metadata

Here we will go through how we can create a package.xml to retrieve metadata from Salesforce. Common metadata type samples are also included.

Metadata type names can be tricky and it usually difficult to create a package.xml without some googling. Here we provide a sample package.xml with examples of common types.

Once you have a package.xml, it is relatively easy to retrieve metadata using it and deploy to other environments. There are multiple options for that- Force.com Migration tool/ANT (Outdated), SFDX (Recommended)- How to retrieve code using SFDX CLI.

Package.xml sample with common metadata types

When you are creating package.xml, copy below simple package.xml file as a starting point

Now copy relevant types from below xml and add to your package.xml. Then go to your org and add members tags for the elements you want to retrieve


Setting up Skill based routing in Salesforce Omni-Channel

Salesforce Omni-channel feature is used to route work to agents in real time based on the routing configuration you define. You can use this feature to route cases, leads, chats, social posts, custom objects etc to the users you need.

Configuring simple Omni-channel setup to route records to agents is complex. It becomes even more complex when you are trying to route records to users/agents based on their skills. Here we outline the steps needed for simple omni-channel routing and skill based omni-channel routing

Simple Omni-Channel Routing

  1. Enable Omni Channel
    • Setup => Check "Enable Omni-Channel" checkbox
  2. Create a Service Channel for your object (can select case, lead, custom object etc)
    • Setup => Service Channel => Click "New" and create a service channel for the object you need
  3. Create Routing configuration
    • Setup => Routing Configuration => New
    • Routing Models (Least Active => Person with least number of cases, Most Available => Can give different capacity for agents - eg junior agents get half capacity)
  4. Create queues and assign routing configuration from previous step
  5. Create Presence Configuration
    • Setup => Presence Configuration => New
    • Can specify max capacity per agent
  6. Create Presence Statuses
    • Setup => Presence Status => New
    • Examples - busy, available etc
  7. Assign statuses to profile
    • Go to the profile and assign statuses to the profile
  8. Add Omni-channel component to app
    • Create/Edit any console app and add "Omni-Channel" component to the utility bar
  9. Go to "Omni Supervisor" tab and you will be able to see status of agents

End to end walkthrough ( Credits to Salesforce Exclusive channel)



Omni-Channel configuration with Skill based routing

  1. Enable Omni Channel
    • Setup => Check "Enable Omni-Channel" checkbox and "Enable Skill-based routing" checkbox
  2. Create a Service Channel for your object (can be case, lead, custom object etc)
    • Setup => Service Channel => Click "New" and create a service channel for the object you need
  3. Create Skills
    • Setup => Skills => New
    • Usually languages and product family names are used as skills
  4. Create Service Resource
    • Created from "Service Resource" tab. This basically registers users as agents who are ready to work on records
    • Service resources can be assigned with skill in "Skills" related list with optional start date and end date
  5. Route cases to agents
    • Routing using Apex
      • Create trigger/process builder that runs apex when a new case is created
      • Insert PendingServiceRouting record in IsReadyForRouting value as false
      • Create "SkillRequirement" record with skills required as junction record between PendingServiceRouting and skill. Use case description/other fields to find skills required
      • Change IsReadyForRouting value to true on PendingServiceRouting records
    • Routing using Flow
      • Create an auto launched flow that gets called on case creation
      • Use "Routing" action and pass (record Id, configuration Id and skill Ids). Salesforce will take care of routing.
      • If flow based routing is used routing configuration also needs to be created
  6. Create Presence Configuration
    • Setup => Presence Configuration => New
    • Can specify max capacity per agent
  7. Create Presence Statuses
    • Setup => Presence Status => New
    • Examples - busy, available etc
  8. Assign statuses to profile
    • Go to the profile and assign statuses to the profile
  9. Add Omni-channel component to app
    • Create/Edit any console app and add "Omni-Channel" component to the utility bar
  10. Go to "Omni Supervisor" tab and you will be able to see status of agents

End to end walkthrough ( Credits to Salesforce Exclusive channel)


Using Lightning Message Service to communicate between lightning components and visualforce

Lightning message service allows you to communicate between all UI technologies of Salesforce (LWC, Aura and Visualforce). This is the recommended way to communicate between lightning components and Visualforce.

Lighting message service communication works in below three steps

  1. Create a new MessageChannel metadata file and deploy to your org
  2. Publish a message from one of the three UI technologies
  3. Subscribe to the message in any of the three UI technologies

1) Creating new MessageChannel

Currently Salesforce do not provide any option in the UI to create MessageChannel. So you have to deploy it as metadata. isExposed setting in metadata allow you to enable communicate between different namespaces/managed packages.

Copy below code metadata to messageChannels folder in your code folder. Name the file as CarSelectionChannel.messageChannel-meta.xml


If you have sfdx installed, you can use below line to deploy the file.

sfdx force:source:deploy -p "pathToFile" -u targetOrgAliasHere

2) Publish event on the MessageChannel

This step varies depending on the whether you are publishing it from LWC or Aura or Visualforce. Our example scenario outlines subscribing and publishing from all three technologies.

3) Subscribing to events on MessageChannel

This step also varies depending on the whether you are publishing it from LWC or Aura or Visualforce. Our example scenario outlines subscribing and listening from all three technologies.

Visualforce Example

Here we use sforce.one methods. This do not work as a stand alone visualforce page. Make sure you are inside lightning experience. ie create a visualforce page with below code, create a tab for that visualforce page and check from lightning experience.

Aura Example

Here we use lightning:messageChannel in the component to subscribe to event.

LWC Example

Here we import @salesforce/messageChannel/CarSelectionChannel__c in JavaScript controller. Also we use subscribe, unsubscribe methods imported from lightning/messageService to subscribe to event.

Please note that if you are just publishing message to channel and not listening to it, you just need to import publish method and the channel. Then you can use the code in handleCarSelect method to publish message to the channel.

Create app builder page to see the result in one page

In order to confirm that the event is getting published and received in all three technologies, put above visualforce, aura and lwc components in a new App builder page and add the page to any app. It should looks like the screenshot at starting of this post.

All ways to communicate between lightning components (Aura and LWC)

There are a lot of different ways to communicate between different types of lightning components (lwc to lwc, lwc to aura, aura to lwc etc). In this blog we will cover all different ways of communicating between different types of lwc and aura components.

Communication patterns between Lightning components


Interactions with Visualforce Page

Still some features like PDF rendering are only supported in Visualforce. There is a chance you might need to interact between lightning components and visualforce components. Some examples are listed below,

  • Embedding visualforce page inside aura [COMING SOON]
  • Embedding aura app inside visualforce [COMING SOON]
  • Embedding visualforce page inside lwc [COMING SOON]
  • Embedding lwc inside visualforce page [COMING SOON]

Query all fields in an object using SOQL

Currently Salesforce does not allow you to query all fields in an object using wild card selectors. Even though it is usually not a best practice to query all fields in an object, sometimes it is useful to query all fields for debugging purposes

Simple way to query all fields in a object in single line is like below,

Database.query('SELECT ' + String.join(new List(Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap().keySet()), ',') + ' FROM Contact');


This will be very handy while debugging. But please note that this is not the optimal way of doing this. If you are doing it in multiple places in code, it is recommended to cache the describe calls. An example of caching Schema.getGlobalDescribe() can be found in the blog How to get RecordType Id efficiently in Apex with caching

Script to deploy source/SFDX format code to your sandbox

Salesforce has two differnt formats to store code/metadata now. Conventional Metadata format and new Source/SFDX format.

Usually you can tell the format from folder structure and file format. If code is following some folder structure like force-app/main/default usually it will be in source format. But is it not guaranteed. A better way to confirm is to check object and field metadata files. If field metadata is included inside a .object file, that means that the code is in metadata format. In source/SFDX format, field metadata will be separated into separate files

Script to deploy source format code to sandboxes

Even if we use scratch orgs for development, we still need to use sandboxes for testing, UAT, training etc. We need to convert code in source format to metadata format before can properly deploy the whole codebase to these sandboxes or production. Use below shell script to make this metadata conversion and deployment easy.

How to use

  • Create a shell file with .sh extension inside your project folder and copy paste above code.
  • Make the file executable with sudo chmod u+x pathToTheShellFileHere.
  • Authenticate your sandboxes/production using sfdx force:auth:web:login command
  • Now to deploy you can navigate to the project folder and run ./shellFileName.sh. It will ask for alias of the environment that you want to deploy to. Enter the alias and hit enter. Deployment starts.

Please note that this shell script works in Mac terminal and Linux shell only. If you are using windows, you can try to use bash shell there or write windows versions of the commands into a .bat file.

How to get RecordType Id efficiently in Apex with caching

It is very common needing to get recordtypeId when we are working in Salesforce. There are multiple ways to do it. Here we will go through different ways and find the best way.

Different approaches

  1. SOQL against RecordType standard object

    [SELECT Id, Name FROM RecordType WHERE Name = 'Master' AND SObjectType = 'Account']

    This approach count against the number of SOQL queries.

  2. Get recordtype ID in apex without caching

    Since this approach do not cache operations like Schema.getGlobalDescribe() and sotype.getDescribe().getRecordTypeInfosByName() performance will not be great

  3. Get recordtype ID in apex with caching USE THIS APPROACH

    Here we cache expensive schema describe operations. Allowing multiple calls to the same method to perform efficient and fast in same transaction.

    You can get recordtype Id using the syntax RecordTypeUtilWithCache.getRecordTypeId('Account', 'RecordTypeNameHere');

CTA Notes : Integration Architecture 1

When you prepare for Certified Technical Architect (CTA) certification, you need to have a lot of details readily available in your memory.

Here we will go through Integration Architecture related topics you need to keep in mind for CTA review board. We will skip some beginner level topics in this series to reduce the length.


Integration Patterns


1) Remote Process Invocation—Request and Reply

Salesforce calls remote system, waits for it to process the request, and makes updates based on response.
Patterns
  1. Enhanced External Services => Config way to invoke external REST services that gives OpenAPI 2.0 JSON schema format (Recommended Approach)
  2. UI element => User Action => Invoke Apex => Call out (Recommended Approach)
  3. Apex Trigger => asynchronous method => Call out
  4. Apex Batch => Call out
Considerations
  • Error Handling(Shown to user), Recovery (Changes are not saved in Salesforce till success response)
  • Idempotent Design Considerations => Guarantee that repeated invocations are safe. (deduplication, pass unique Id etc)
  • Security => One way SSL is enabled by default. Two way SSL (Self-signed/CA signed certs) can be enabled if needed, Can add one way hash/digital signature using crypto to ensure request authenticity, firewalls for remote system
  • Governor Limit => Max timeout is 120 secs, Can have only 10 requests that takes more than 5 secs to execute (Long running callout). To avoid set timeout to 5 sec / use continuation

2) Remote Process Invocation—Fire and Forget

Salesforce calls remote system, remote system acknowledges the request, Salesforce continues processes without waiting.
Patterns
  1. Platform events (Can be done through config/code)
  2. Outbound Messaging => Sending SOAP message from DML operations that fire workflow (Create/Edit), Salesforce retries if the system didn't respond
  3. Outbound Messaging with callback => Can send sessionId along with message. External system can use this session ID to access Salesforce REST/SOAP API to get more details about same record/other related records OR update result back to Salesforce.
  4. UI Component triggering Async callout => controller => callout => External system acknowledges and continues processing asynchronously
  5. Trigger => Async apex callout => external system
  6. Batch job => Apexbatch => Callout to external system
Considerations
  • Error Handling
    Callout => Remote system must handle errors that occur during asynchronous processing,
    Outbound message => Salesforce retries(15sec - 60min) up to 24 hours, external system must handle processing errors. Failures can be found in a queue for admins to monitor.
    Platform Events => Cannot rollback, replay ID can be used to get old events(upto 72 hours) after previous successful processing, Two options("Publish after Commit", "Publish Immediately")
  • Idempotent Design Considerations => Guarantee that repeated invocations are safe. (deduplication, pass unique Id etc)
  • Security Outbound Messaging=> One way SSL is enabled by default. Two way SSL can be enabled with "Outbound Messaging Certificate", IP whitelisting
  • Governor Limit => Max timeout is 120 secs, Can have only 10 requests that takes more than 5 secs to execute (Long running callout). To avoid set timeout to 5 sec / use continuation

3) Batch Data Synchronization

Two way data synchronization between Salesforce and external system.
Patterns
  1. Change Data Capture => Salesforce publishes change events for (CRUD, undelete) operations, near real time
  2. Replication using ETL tool => To send to Salesforce, we can use Bulk API, SOAP API, See if we can find ETL that supports change data capture against external system To extract from Salesforce, Use time/status to filter rows. There is a getUpdated() method in SOAP API.
  3. Remote Call-In & Remote Call-Out => Real time update, can cause a lot of taffice, special consideration on error handling, locking, can cause perofrmance issues
Considerations
  • ETL tools uses control tables to store last job time, and other values related to previous runs that can be used to filter the data that needs to be synced.
  • Use primary keys in both systems to match incoming data
  • Surrogate keys are anonymous integer primary keys without business meaning to do transformation
  • Get only updated data
  • Group child table loads(contact) by parent(accountId) to avoid locking/failure
  • Disable Triggers, workflow rules etc if not important

4) Remote Call-In

External system makes inbound request to make changes to Salesforce data. It is very common for companies to keep sales and service in Salesforce and order management in external system. In this case external system needs to update order status to Salesforce.
Patterns
  1. SOAP API => Can publish event (Syntax is like object creation) Enterprise WSDL & Partner WSDL can be used. Can create custom SOAP endpoint for complex transaction management
  2. REST API => Lightweight alternative for SOAP, No predefined contract, Composite resources option to make a series of updates in one API callback Composite resources => can use one request response for next input, couted as single API callback Bulk API is REST based
  3. Apex Web Services => For complex transaction support/custom logic, But more maintenance
  4. Apex REST services => Same as Apex Web Services but no need to consume service contract/WSDL
  5. Bulk API => Large volume CRUD.
  6. REST API to invoke an auto launched flow Salesforce
Considerations
  • Authentication => SSL V3, TLS are supported in SOAP API, Ciphers must have at least 128 bit key length.
    REST API cal use OAuth to get a token or use session ID obtained from Outbound message/SOAP API.
    Queries through SOAP API, can timeout after 120 sec.
    Volume Limits => SOAP login request must be less than 10KB, Only upto 3600 login() calls/user/hour Max 2GB for contentversion, 1MB max for event message size, Bulk API (Upto 10k batches/24hours, upto 10k records in a batch)
    For SOAP API, remote system (client) must participate in a contract-first implementation where the contract is supplied by Salesforce (for example, Enterprise or Partner WSDL).
    Custom SOAP webservice/Apex REST service can support cross-object transactions and custom logic, But always check if middleware is suitable to do these.
    An integration user can have up to 10 query cursors open at a time.
    Only 250k events per hour in case of high volumne platform events. Can replay up to 72 hours
    Salesforce APIs do not support reliable messaging protocols like WS-ReliableMessaging

5) UI Update Based on Data Changes

Create custom interface using streaming API to notify user of the changes in data.
Patterns
  1. Streaming API
  2. Platform Events
Considerations
  • Deliver and order of notifications is not guaranteed
  • Notifications are not generated for bulk API operations

6) Data Virtualization

Showing external data in Salesforce in real time without persisting it.
Patterns
  1. Salesforce Connect => maps data tables in external systems(SAP, MicroSoft etc) to external objects in Salesforce org
    External object features :- CRUD operations on external data, can define relations with custom objects, Can access in list views, tabs, page layouts, reports(limited) etc, Can view in Salesforce mobile app, available in global search and lookups, record feeds, apex, SOQL, SOSL, Salesforce APIs, change sets, packages etc, Can use Salesforce connect validator app to test connection.
    Can use one of the three connectors
    • OData 2.0/OData 4.0 connector to connect to OData producers
    • Cross-org adapter to connect to another Salesforce org using REST API
    • Custom adapter created via Apex => custom using Apex Connector Framework
  2. Request and Reply => Callout to external system using SOAP/REST protocol to call out
Considerations
  • Timeliness => User is waiting, max callout timeout is 120 sec, long running callout limits
  • Relationships => Lookup(Using Salesforce record Id as parent), External Lookup(Using external ID standard field for lookup), Indirect lookup (custom external and unique field for lookup)
  • Volume restrictions & rate limiting exist

Integration Pattern Categories

  • Data Integration - Syncing data. Often includes often include aspects of master data management (MDM), data governance, mastering, de-duplication, data flow design, and others.
  • Process Integration - Two or more apps integrated for completing business process.
    • orchestration (where one application is the central “controller”)
    • choreography (where applications are multi-participants and there is no central “controller”).
    complex to design & test, Needs to consider capabilities of systems, transactionality, Exception handling etc.
  • Virtual Integration - Interacting with data in another system without copying to Salesforce.
Pattern Selection Matrix
Integration Terms
  • Process choreography => mulitple systems working together without central authority
  • Service orchestration => Single central system coordinating activities of other systems
  • Transactionality => Support ACID (atomicity, consistency, isolation, durability). If complex multi-system transactions are required, go for middleware.
  • Long polling/Comet Programming => Client keeps a connection open to server. Bayeux is a protocol for transporting asynchronous messages. CometD is a scalable HTTP-based event routing bus that implements Bayeux protocol. Streaming API uses this. Websockets => Establishes two way communication channel, Server Side Events => server publishes and clients listens are alternatives.
  • Reverse Proxy Server => Receives requests on behalf of one or more servers, makes requests internally and returns results. Help to increase security, performance and reliability. Appache HTTP, nginx, IBM Webseal etc
  • more on encryption

Communication between independent lightning web component and Aura component - aurapubsub

You can use pubsub library or lightning message service to communicate between components that are not in same DOM hierarchy. These methods can be used to communicate between sibling components in an outer lwc component or between to lwc components that are dropped separately in lightning app builder.

Here we will go through an example of lwcComponentA that displays three car company names using radio button. When a car company is selected in the child component we will fire a carselected event from child component with the name selected by the user. Parent component will listen to this event and display the selected name in parent component. Parent component auraComponentB, will listen to this event and display the selected name in auraComponentB.

Example

1) Create a utility lwc component with name pubsub. Copy paste below code into it's JavaScript file. Please note that this is a utility component provided by Salesforce. But current version available in the link is doing pageRef check and it is not working as expected. So use below version shared by another Salesforce team member instead.


2) Create a utility lwc component with name auraPubSub Copy paste below code into it's JavaScript file.Please note that this is a utility component provided by Salesforce.


3) Create a lwc component with name lwcComponentA


4) Create a aura component with name auraComponentB


5) Create a aura test app lwcToAuraSiblingTest in which lwcToAuraSiblingTest.App can contain both components

6) Now if you open the aura app, it will look like

child to parent lwc communication

Explanation

In lwcComponentA component, when value of car is changed in the radio button, it calls JavaScript method in controller sendDataToComponentB. This function uses fireEvent method in pubsub library and fires a custom event with name carselected. Selected carname is also passed as data in the event payload.

auraComponentB component, has a listener added for carselected event. It is achieved by using registerListener method in auraPubsub utility. Inside handlePubsubReady methos we add a listener using the line registerListener('carselected', callback);. This basically tells "whenever a carselected event is received, go to callback inside handlePubsubReady method in JavaScript controller.

Finally when diplaySelectedCar method is called, we take value from the event payload and assigns to valueGotFromA variable in JavaScript

Things to Note

  • This is a common pattern to pass values between independent aura and lwc components in same page.
  • Make sure that you are using the pubsub and auraPubsub libraries shared above. Otherwise you might get an error pubsub listeners need a "@wire(CurrentPageReference) pageRef" property.

Communication between independent lightning web components - pubsub

You can use pubsub library or lightning message service to communicate between components that are not in same DOM hierarchy. These methods can be used to communicate between sibling components in an outer lwc component or between to lwc components that are dropped separately in lightning app builder.

Here we will go through an example of lwcComponentA that displays three car company names using radio button. When a car company is selected in this component we will fire a carselected event from lwcComponentA with the name selected by the user. A separate lwcComponentB, that is outside direct DOM hierarchy of lwcComponentA, will listen to this event and display the selected name in lwcComponentB.

Example

1) Create a utility lwc component with name pubsub. Copy paste below code into it's JavaScript file. Please note that this is a utility component provided by Salesforce. But current version available in the link is doing pageRef check and it is not working as expected. So use below version shared by another Salesforce team member instead.


2) Create a lwc component with name lwcComponentA


3) Create a lwc component with name lwcComponentB


3) Create a parent lwc component with name parentLwc that can contain both components

3) Now if you surface the parent component in lightning experience, it will look like

child to parent lwc communication

Explanation

In lwcComponentA component, when value of car is changed in the radio button, it calls JavaScript method in controller sendDataTolwcComponentB. This function uses fireEvent method in pubsub library and fires a custom event with name carselected. Selected carname is also passed as data in the event payload.

lwcComponentB component, has a listener added for carselected event. It is achieved by using registerListener method in pubsub utility. Inside connected callback we add a listener using the line registerListener('carselected', this.diplaySelectedCar, this);. This basically tells "whenever a carselected event is received, call diplaySelectedCar method in JavaScript controller.

Finally when diplaySelectedCar method is called, we take value from the event payload and assigns to valueGotFromA variable in JavaScript

Things to Note

  • This is a common pattern to pass values between independent lwc components in same page.
  • Make sure that you are using the pubsub library shared above. Otherwise you might get an error pubsub listeners need a "@wire(CurrentPageReference) pageRef" property.

Communicating from child lightning web component to parent lightning web component

You need to fire CustomEvent from child component to communicate to a parent component.

Here we will go through an example of a child component that displays three car company names as a radio button. When a car company is selected in the child component we will fire a carchange event from child component with the name selected by the user. Parent component will listen to this event and display the selected name in parent component.

Example

1) Create an lwc component with name childLwc


2) Create an lwc component with name parentLwc

3) Now if you surface the parent component in lightning experience, it will look like

child to parent lwc communication

Explanation

In childLwc component, when value of car is changed in the radio button, it calls JavaScript method in controller sendDataToParent. This function then dispatches/fires a custom event with name carchange. For every custom event, if you are passing data, you need to pass it as a JSON object with detail attribute.

parentLwc component, has a listener added for carchange event. It is achieved by adding on+eventname attribute while refering child component in html. In our case it is oncarchange attribute added at line 5 of parentLwc component html. This basically tells "whenever a carchage event is received, call displayValueInParent method in JavaScript controller.

Finally when displayValueInParent method is called, we take value from the event.details and assigns to valueSentByChild variable in JavaScript

Things to Note

  • This is a very common pattern to pass values from child component to parent component
  • Make sure that you are using detail attribute while sending data
  • Make sure that your event name is all small letters. ie carchange instead of carChange
  • Make sure that your listener name is all small letters. ie oncarchange instead of oncarChange

Communicating from parent lightning web component to child lightning web component

It is easy to communicate/send data from a parent lightning web component to a child lwc component. You can define a variable in the child lwc component javascript file, annotated it with @api annotation and finally pass value from parent component to the child component by using this variable name.

Example

1) Create an lwc component with name childLWCComponent


2) Create an lwc component with name parentLWCComponent

If you surface the parent component in lightning experience, it will looks like

parent to child lwc communication

Explanation

Here childLWCComponent has a javascript variable childVariable annotated with @api annotation. Parent component can pass value using this attribute name. But please note that camel case variable names in child component is converted to kebab case in parent component.

Use Cases

This is the most common form of communication/exchange of data between lwc components. Usually complex lightning apps are built as a combination of multiple child lwc components. ie a parent lwc component contining multiple child lwc components. This parent component will retain data that is needed by all child components and sends it to child components using variables defined in child component using @api annotation.