Thursday, December 23, 2021

Platform Events And Examples how to create in Salesforce

 Platform Event is based on Event-Driven Architecture which enable apps to communicate inside and outside of Salesforce. Platform events are based on the publish/subscribe model and work directly with a message bus which handles the queue of incoming events and processes listening for them. This is built in real time integration patterns in the Salesforce Platform which helps to reduce point-to-point integration


Here is some terminology we should remember :-
  • Event : A change in state that is meaningful in a business process.
  • Event message / Notification : A message that contains data about the event.
  • Event producer : The publisher of an event message over a channel.
  • Channel : A conduit in which an event producer transmits a message. Event consumers subscribe to the channel to receive messages. Also referred to as event bus in Salesforce.
  • Event consumer : A subscriber to a channel that receives messages from the channel.

Understanding of Platform Event

  • SObject like Salesforce Entity
    • Suffixed with __e
    • ReplayId fir replaying specific event
    • Only Checkbox, Date, Date/Time , Number , Text and Text Area field available.
  • Pub / Sub based communication 
    • No Polling required.
  • Heterogeneous playloads
    • Define events with different playloads

Difference between SObject and Platform Events


SObjects__c
Platform_Events__e
DMLs (Insert, Update, Delete)
Publish (Insert only)
SOQL
Streaming API
Triggers
Subscribers
Parallel context execution
Guaranteed order of execution

Considerations :-

  1. Platform event is appended with__e suffix for API name of the event.
  2. You can not query Platform events through SOQL or SOSL.
  3. You can not use Platform in reports, list views, and search. Platform events don’t have an associated tab
  4. Published platform events can’t be rolled back.
  5. All platform event fields are read-only by default
  6. Only after insert Triggers Are Supported
  7. You can access platform events both through API and declaratively
  8. You can control platform events though Profiles and permissions

Publishing / Subscribing Platform Events



Publish Platform Events :


We can publish the platform events in 3 ways:
  1. Publish Events Messaging using APEX.
    List<Order_Shipping__e> orderShippingList = new List<Order_Shipping__e>();
    Order_Shipping__e orderShipping = new Order_Shipping__e( Order_Number__c='12345', status__c=1 );
    orderShippingList.add(orderShipping);

    List<Database.SaveResult> results = EventBus.publish(newsEventList);

    for (Database.SaveResult sr : results) {
        if (sr.isSuccess()) {
            System.debug('Successfully published event.');
        } else {
            for(Database.Error err : sr.getErrors()) {
                System.debug('Error returned: ' + err.getStatusCode() );
            }
        }
    }
  2. Publish Events Messaging using Declarative tools 
    1. Process Builder 
    2. Cloud Flow Designer Tool / Visual Work flow
  3. Publish Events Messaging using Salesforce API from external app.

Subscribing Platform Events :


We can subscribe the platform events with following ways :
  1. Apex Trigger : Write an “after insert” Apex trigger on the event object to subscribe to incoming events.Triggers receive event notifications from various sources—whether they’re published through Apex or APIs.

    Trigger OrderShippingTrigger on Order_Shipping__e (after Insert) {
      
    }
  2. Subscrbe to platform event notification in Lightning components
    1. Lightning web components :  Use the empApi methods in your Lightning web component, import the methods from the lightning/empApi module as follows

      import { subscribe, unsubscribe, onError, setDebugFlag, isEmpEnabled }
          from 'lightning/empApi';
    2. Subscibe in an Aura Component : Use the empApi methods in your Aura component, add the lightning:empApi component inside your custom component and assign an aura:id attribute to it
      <lightning:empApi aura:id="empApi"/>
  3. In an external app, you subscribe to events using CometD as well.
  4. Flow and process builder. Check this post.
Please check below two Apex Hours sessions to learn more about platform event.
  1. Platform Event basics
  2. Overcome Salesforce Governor Limits Using Platform Events
 --------------------------------------------------------------------------------------------------------------------------------------

Introduction: 

Platform Events are used to deliver secure, scalable, and customizable notification within Salesforce or external app. Platform Event is based on Event-Driven Architecture. This is built in real time integration patterns in the Salesforce Platform which helps to reduce point-to-point integration.

Publishing platform event: 

We can publish the platform events in 3 ways:

  1. Publish Events Messaging using APEX.
  2. Publish Events Messaging using Declarative tools (Process Builder or Cloud Flow Designer Tool / Visual Work flow).
  3. Publish Events Messaging using Salesforce API from external app.

Not supported in Platform event: 

  1. The allOrNoneHeader API header is ignored when you publish platform events through the API.
  2. The Apex setSavepoint() and rollback() Database methods aren’t supported with platform events.

Subscription in Platform Event: 

  1. Apex triggers receive event notifications.
  2. write an “after insert” Apex trigger on the event object to subscribe to incoming events.
  3. Triggers receive event notifications from various sources—whether they’re published through Apex or APIs.
  4. Visualforce and Lightning component apps receive events through CometD.
  5. CometD is a scalable HTTP-based event routing bus that uses an AJAX push technology pattern known as Comet.
  6. In an external app, you subscribe to events using CometD as well.

Defining Objects and fields in Platform Events: 

Platform events can be created just like the custom objects. The biggest difference between Platform events and Custom object is suffix name for the api name. In Platform events, its api name suffix with __e where the custom object appends __c suffix to create api name. Unlike with custom objects, we cannot update or delete event record, or view event records in Salesforce User Interface.

Platform Events support only following custom fields type,

  1. Checkbox
  2. Date
  3. Data/Time
  4. Number
  5. Text
  6. Text Area (Long)

ReplayId System Field and Event Retention

  1. Salesforce stores platform events for 24 hours. You can retrieve stored events in API clients but not in Apex.
  2. Each event record contains a field, called ReplayID, that the system populates after the event is published.
  3. Each replay ID is guaranteed to be higher than the ID of the previous event, but not necessarily contiguous for consecutive events.
  4. You can retrieve all stored events, or you can specify the replay ID of an event as the baseline for the retrieved portion of events.

Steps to Create and Publish Platform Events:

  1. From Setup, Search Platform Events and Click on the Platform Events.
platform events salesforce
  1. Click on New button to create Platform Events.
  1. Provide the name for the Platform Events.
platform events salesforce
  1. Create a custom field to show the Notification from this field.
platform events salesforce
  1. Create an Apex Class to publish the Platform Event

NotificationController.cls

platform events salesforce
  1. Create a Lightning Component to subscribe the Platform Event through cometd JavaScript client and get the real-time notification through this component.

helpNotification.cmp:

platform events salesforce

helpNotificationController.js

platform events salesforce

helpNotificationHelper.js

platform events salesforce
  1. From Setup > App Manager > Click Edit on Service Console App.
platform events salesforce
  1. Click on Utility Bar Tab. Click on Add button and choose helpNotification component to add lightning component to Service Console App.

v

  1. Provide the component name as Help and check Load in background apps open option.
  1. Go to the Service Console App. You will see the notification as shown below and Help utility bar.
platform events salesforce
  1. Click on any case record. In Chatter feed, Add #Help with your custom message in chatter feed.
platform events salesforce
  1. Upon posting the message with #Help, it will show the notification on which the platform events have been published. Also, you will get notification in Help Utility bar.
platform events salesforce

Conclusion: 

It is no longer applications are pulling out from multiple endpoints and polling to retrieve the data. We can get the data by subscribing to the platform event. It will help create 360-degree customer experience to get the information when the data changes.

----------------------------------------------------------------------------------------------------------------------

Salesforce event-driven architecture is consisting of

  • event producers
  • event consumers
  • channels. 

Platform events simplify the process of communicating changes and responding to events. Publishers and subscribers communicate with each other through events. One or more subscribers can listen to the same event and carry out actions.

With an Event-driven architecture each service publishes an event whenever it updates or creates a data. Other services can subscribe to events. It enables an application to maintain data consistency across multiple services without using distributed transactions. 

TrailheaDX 2019 : Explore New Frontiers with High Volume Platform Ev…

Let us take an example of order management. When the Order management app creates an Order in a pending state and publishes an Order Created event. The Customer Service receives the event and attempts to process an Order. It then publishes an Order Update event. Then Order Update Service receives the event from the changes the state of the order to either approved or canceled or fulfilled. The following  diagram show the event driven architect

An Introduction to Salesforce Platform Events - SFDC Beginner

Terminology

Event

A change in state that is meaningful in a business process. For example, a placement  of an order is a meaningful event because the order fulfillment center requires notification to process the order.

Event Notifier

A message that contains data about the event. Also known as an event notification.

Event producer

The publisher of an event message over a channel.

Channel

A conduit in which an event producer transmits a message. Event consumers subscribe to the channel to receive messages.

Event consumer

A subscriber to a channel that receives messages from the channel. A change in state that is meaningful in a business process.

But when you overlook at Platform events it makes similar to Streaming API and most of the futures including the replayID and durability but below makes the difference between with streaming API.

  • Platform  events are special kinds of entity similar to custom object
  • You can publish and consume platform events by using Apex or a REST API or SOAP API.
  • Platform events integrate with the Salesforce platform through Apex triggers. Triggers are the event consumers on the Salesforce platform that listen to event messages.
  •  Unlike custom objects, you can’t update or delete event records. You also can’t view event records in the Salesforce user interface, and platform events don’t have page layouts. When you delete a platform event definition, it’s permanently deleted.
  • Platform events may be published using declarative tools (Process Builder)
  • platform events can also be subscribed to using APEX  or decoratively process builder      and flows

Publishing and subscribing Platform events

Publishing and subscribing the platform event are more flexible. You can publish event messages from a Force.com app or an external app using Apex or Salesforce APIs and you can subscribe from the Salesforce or external apps or use long polling with cometD as well.

Define Plat form Event

Define platform event similar like custom object, go to setup –> develope –> Platform events –> create new platform events as shown below.

Publish Platform events

1.a. Publish Using Apex

A trigger processes platform event notification sequentially in the order they’re received and trigger runs in its own process asynchronously and isn’t part of the transaction that published the event. Salesforce has a special class to publish the platform events EventBus which is having methods publish method. once the event is published you can consume the events from the channel

trigger PlatformEventPublish on Account (after insert , after update ) {
    
    If(trigger.isAfter && trigger.isUpdate){
        List<Employee_On_boarding__e> publishEvents = new List<Employee_On_boarding__e>();
        for(Account a : Trigger.new){
            Employee_On_boarding__e eve = new Employee_On_boarding__e();
            eve.Name__c = a.Name ;
            eve.Phone__c = a.Phone ;
            eve.Salary__c = a.AnnualRevenue ;
            publishEvents.add(eve);            
        }
        if(publishEvents.size()>0){
            EventBus.publish(publishEvents);
        }
        
    }
    
}

1.b. Publish Using Process Builder

1.c. Publish Events by Flow

Create flow: 1(platform Event producer)

Create flow:2(Platform Event Consumer)

Run/Debug Flow:1(platform Event producer) and you will send post in chatter.

Result:

1.d. Publish Events by Using API (Using workbench)

Subscribe for Platform events

We can subscribe to the platform events from the Platform events object trigger which is created in step 1. Here is the sample trigger show how you can handle the subscribed events. create new accounts from the platform event but you can implement your own business logic to update the data.

Using Trigger:

trigger OnBoardingTrigger on Employee_On_boarding__e (after insert) {
    List<Account> acc = new List<Account>();
    for(Employee_On_boarding__e oBording :trigger.new){
        acc.add(new Account(Name =oBording.Name__c , Phone =oBording.Phone__c , AnnualRevenue = oBording.Salary__c));
    }
    if(acc.size() >0){
        insert acc ;
    }
}

Below is simple visual force page that consumes the platform events which you published. This page is built on cometD.

CometD is a set of library to write web applications that perform messaging over the web.Whenever you need to write applications where clients need to react to server-side events, then CometD is a very good choice. Think chat applications, online games, monitoring consoles, collaboration tools, stock trading, etc. 

you can consume the platform events by using this  URI /event/Employee_On_boarding__e and the Complete code is here below.

<apex:page standardStylesheets="false" showHeader="false" sidebar="false">
    <div id="content"> 
    </div>
    <apex:includeScript value="{!$Resource.cometd}"/>
    <apex:includeScript value="{!$Resource.jquery}"/>
    <apex:includeScript value="{!$Resource.json2}"/>
    <apex:includeScript value="{!$Resource.jquery_cometd}"/>
   
    <script type="text/javascript">
    (function($){
        $(document).ready(function() {
            $.cometd.configure({
                url: window.location.protocol+'//'+window.location.hostname+ (null != window.location.port ? (':'+window.location.port) : '') +'/cometd/40.0/',
                requestHeaders: { Authorization: 'OAuth {!$Api.Session_ID}'}
            });
            $.cometd.handshake();
            $.cometd.addListener('/meta/handshake', function(message) {
                $.cometd.subscribe('/event/Employee_On_boarding__e', function(message) {
                    var div = document.getElementById('content');
                                    div.innerHTML = div.innerHTML + '<p>Notification </p><br/>' +
                        'Streaming Message ' + JSON.stringify(message) + '</p><br>';
                });
            })
        });
    })(jQuery)
    </script>
</apex:page>

Wednesday, December 15, 2021

What is a Flow in Salesforce?

 In Salesforce, a flow is an application that automates complex business processes. Simply put, it collects data and then does something with that data.

Flow Builder is the declarative interface used to build individual flows. Flow Builder can be used to build code-like logic without using a programming language.

Flows fall into five categories:

  • Screen Flows:
  • These are flows that have a UI element and require input from users. These types of flows are either launched as an action or embedded as an element on a Lightning page.
  • Schedule-Triggered Flows:
  • These autolaunched flows launch at a specified time and frequency for each record in a batch, and they run in the background.
  • Autolaunched Flows:
  • Run automated tasks with this flow type. Autolaunched flows can be invoked from process builder, from within an Apex class, from a set schedule, from record changes, or from platform events.
  • Record-Triggered Flows:
  • These autolaunched flows run in the background when a record is created, updated, or deleted.
  • Platform Event-Triggered Flows:
  • When a platform event message is received, these autolaunched flows runs in the background.

Check out this example of a schedule-triggered flow, pulled from a well-known Salesforce group:

Screen Shot 2020-08-14 at 10.40.54 AM.png


When/why should I use a flow?

To answer this question, we really need to look into what automation is needed. In most cases, the type of automation to use for a specific process is determined by evaluating where the data for the processes originates from and where it needs to go. Consider whether what you need to accomplish is best handled by a flow, workflow field update, or a process.

  • Flows are able to create, edit, and delete any record passed into the flow. Records do not have to be related in order to pass data in a flow. Flows can also be scheduled to run on a set interval with a collection of records.
  • The workflow field update can write data to the same record that invoked the workflow rule, or to the master record of a master-detail relationship on the record that invoked the rule. Workflow rules are not able to create, edit, or delete records.
  • Processes, created in the Process Builder, can write data to the same record that invoked the process, or to records related by either lookup or master-detail relationships. Processes can also create records, but they cannot delete them. Processes also cannot query records unrelated to the invoking record.


When should I not use a flow?

Generally, you should not use a flow in the following situations:

  • There is complicated logic involved that is better managed with Apex code. An example of this is the flow shown in the Overview section. The logic in this flow is so complicated that it makes debugging a pain, plus it makes documenting and managing the flow difficult.
  • Your Salesforce edition limits how many flows you can create. Essentials and Professional editions of have a limit of five processes (per process type) and flows (per flow type) in each organization. For most logic in these editions, it is easier to use a process.


How do I create a flow in Salesforce?

  • Open Flow Builder. From Setup, enter “Flows” into the Quick Find box, select Flows, and then click New Flow.
  • Select the Flow Type, then click Create.
  • Drag the elements you want to use onto the canvas. Each element represents an action that the flow can execute. Examples of such actions include reading or writing Salesforce data, displaying information and collecting data from flow users, executing business logic, or manipulating data.
  • Connect the elements to determine the order in which they’re executed at run time. Don’t forget to connect the Start element to another element!
  • Save your flow.

After you build a flow, make sure that it’s working correctly by thoroughly testing it. Once you’ve tested it, activate the flow. You’re now ready to distribute the flow to users.

Pro tip: Flows can be executed in several ways, depending on who the flow is designed for. Internal users, external users, or systems can run a flow, or a flow can be deployed for another organization. Just remember, no matter how you execute it…you’ve got to go with the flow.


Flows vs. Apex

  • Apex code requires a developer and Sandbox to deploy, meaning it can only really be built in organizations using a Professional or above edition of Salesforce. Flows can be built in all editions, as a Sandbox is not required for deployment.
  • Apex is not available in Essentials, and some Apex features are limited in Professional. Organizations with Enterprise and above have no Apex limitations, but flow features are not limited based on the edition.
  • Apex code requires constant development and discipline to maintain. Flows require less work to keep up-to-date.
  • Flows can be built by admins, while Apex code is typically built by developers only.
  • Apex code is considered a tool of last resort. Flows are simpler and should be used before Apex code.
  • If the logic is too complex, Apex code should be used. There is unlimited potential with Apex; flow capabilities are catching up, but they are still inferior to Apex.
  • Renewal generation, OLI creation, and other pieces of automation that were traditionally built as Apex code can now be built as flows, preserving code space for projects that require Apex.

Apex code should be used in the following scenarios:

  • You’re dealing with complex Salesforce automation that requires multiple steps and actions where a flow will become cumbersome.
  • You need custom-built integrations with other systems (such as a connection to a SQL database that requires bi-directional syncs).
  • ERP integrations are involved.
  • You need to be able to control the batch size of your automation in order to prevent limit errors.
  • You need to present an error message in the UI if the automation fails or doesn’t find what it’s looking for.


Flows vs. Processes

  • Processes are more user-friendly as far setup and management goes.
  • Flows allow you to add screens where users can enter data. Processes do not have this capability.
  • Flows can be invoked, started by users, triggered by a record change, or scheduled to run on their own at a custom time and frequency. A process, however, runs automatically (either immediately or scheduled) when criteria is met. It can also be invoked by another process created in the Process Builder.
  • Both flows and process can include scheduled actions.
  • Flows can be paused by users, but processes run when the criteria is met and cannot be paused.
  • Flows and processes both contribute to CPU limits and other automation limits in Salesforce.
  • Process actions are executed in the order in which they appear in the process definition, but flows can have different and more complex orders of operations.
  • Flows can be built to cycle through multiple unrelated and related objects. Processes, however, are limited to the base object (opportunities, for example) and related objects (accounts).
  • Flows can be designed to run either before or after a record has been saved to the database, but processes can only trigger after a record has been saved.
  • Flows can be designed to trigger upon creation, update, or deletion of a record. Processes can trigger only for creation or updates to a record.
  • Flows can be test-run and run in debug mode on the flow canvas, including in a rollback mode, which allows you to test your automation without making changes to your data.

The following actions are only available for processes:

  • Quip actions
  • Send survey invitation


Flows vs. Workflow Rules

  • Flows are available in all Salesforce editions, including Essentials. Workflow rules (WFRs) are not available in Essentials or Professional editions.
  • WFRs are not actively being updated by Salesforce (but you can still use them for the time being). Flows are constantly being updated with new features and capabilities in each Salesforce release.
  • There are limitations with how many WFRs can be active at once, but they typically do not contribute to CPU limits unless the WFR triggers a process or flow through one of its updates (such as a field update).
  • Both flows and WFRs can have scheduled actions, but WFRs are limited to 1000 triggers per hour.
  • WFRs can only make one decision, but you can call other flows and Apex code with a flow.
  • WFRs are limited to just a few actions: creating a task record, sending an email, updating a field, or sending an outbound message. Flows can do all of these actions and many more.


Testing Flows

To test a flow, click the Debug button on the canvas, input your variables, and click Run. Then run through the flow to make sure it works properly. This process is especially helpful with screen flows.

Note that as of the Winter 2021 Salesforce release, a beta feature called Debug on Canvas is available. This feature makes flow debugging easier by visually demonstrating the path your flow will take when it runs. It also shows query limits of the flow in the debug details. Additionally, debugging now offers a two more options than it did previously: Run flow as another user, and Run flow in rollback mode.


Where is the Flow Builder in Salesforce?

To find the Flow Builder in Salesforce (Lightning) navigate to Setup > Process Tools > Flows.

Setup.png
Screen Shot 2020-08-10 at 11.03.20 AM.png


What are the different Flow Types in Salesforce?

Auto-Launched Flows with No Flow Trigger

These flows don’t require user interaction, and they don’t support screens, local actions, choices, or choice sets. The available distribution methods available are:

  • Flow actions
  • Lightning pages
  • Lightning community pages
  • Custom Aura components
  • Custom Lightning web components
  • Custom buttons or custom links
  • Web tabs
  • Direct flow URLs
  • Visualforce pages
  • Lightning out
  • Embedded service deployments

Auto-Launched Flows with a Schedule Trigger

These flows only run from a schedule that the user sets. They don’t support user interaction, screens, local actions, choices, or choice sets. The available distribution methods are:

  • Processes
  • Custom Apex classes
  • REST API
  • Web tabs
  • Custom buttons or custom links
  • Visualforce pages

Screen Flows

Screen flows require user interaction because they include screens, local actions, steps, choices, or dynamic choices. Screen flows don’t support Pause elements. A schedule-triggered flow only runs at the scheduled time and frequency.

Auto-Launched Flows with a Record Trigger

These flows are designed to quickly make simple changes to a record when the record is created, updated, or deleted. They can also be configured to make those changes either before or after the record has been saved to the database. In a before-save flow, the supported elements are AssignmentDecisionGet Records, and Loop. After-save flows have access to all flow capabilities, but they cannot launch sub flows.

User Provisioning Flow

User provisioning flows provision users for third-party services. You could use this flow type to customize the user provisioning configuration for a connected app, linking Salesforce users with their Google Apps accounts. A user provisioning flow can only be implemented by associating it with a connected app when running the User Provisioning Wizard.

Field Service Mobile Flow

These flows require user interaction because they have one or more screens.

Field Service Embedded Flow

These flows require user interaction because they have one or more screens.

Contact Request Flow

These flows require user interaction because they have one or more screens. Use one of the following Experience Builder components to add this flow:

  • Contact Request Button & Flow (launch the flow in a popup window)
  • Flow (embed the flow directly on the page)

For more on Flow Types in Salesforce, check out the official documentation.


What is a flow interview in Salesforce?

While a flow is an application built by your administrator that asks you for inputs and does something in Salesforce based on those inputs, a flow interview is a running instance of a flow.

For example, a flow could provide a call script for customer support calls using the information you provided to create a case. What the flow does with the information you provide is entirely up to your administrator.

When you run a flow interview, whether through a link, button, or tab, you’re running a single instance of a flow. If the terminology is confusing, consider the difference between a record and an object. You create an account record, which is a single instance of the account object that your administrator customized.

Read more about flow interviews in Salesforce’s documentation.


How do you call a flow from a button in Lightning?

Since Winter 2018, Salesforce has offered an easy way to trigger a flow using a Quick Action button in Lightning.

Note: Only screen flows or field service mobile flows may be launched from a Quick Action button.

  1. Create a custom action for the record in question by navigating to Object Manager > (Object Name) > Buttons, Actions and Links.
  2. Select “Flow” as the type for the custom action.
  3. Configure the custom action to reference the flow, then name it.
  4. Add the custom action to the page layout of your choice.


Common Mistakes When Designing Flows

We see a lot of flows here at Kicksaw, and we build even more of them. Here are some common and avoidable mistakes we’ve identified:

  • Using the wrong field or variable
  • Not checking for null values
  • Too many SOQL queries
  • Object & field-level security for running user
  • No access to running flows


Using PRIORVALUE of a record in a Lightning flow

Salesforce allows you to add access to the PRIORVALUE of a record in a Lightning flow, in a way that is similar to the way the Process Builder worked. This brings flows to the next level.

After selecting the object, Salesforce will automatically create a record variable ($Record__Prior) for it. You will then be able to refer to it anywhere in the flow.