Monthly Archives

  • Lightning Message Service

    In this blog post, we would be creating Visualforce, Aura Component and Lightning Message Service and exchanging messages between all of them using Lightning Message Service.

    Introduction to Lightning Message Service

    • Introduced in the Winter ’20 release by Salesforce, Lightning Message Service is the out-of-the-box functionality that empowers you to communicate between Visualforce and Lightning Components, including Aura web components (AWC) and Lightning web components (LWC).
    • For an organization hesitant to migrate to Lightning Experience and its newer technologies, Aura Components and Lightning Web Components.
    • LMS may make the migration palatable. With LMS’s ability to communicate between Visualforce pages and lighting components, you can take a more disciplined approach to upgrading.
    • Instead of scraping existing Visualforce pages and creating new Lightning components, you can update existing Visualforce pages to interact with new Lightning components to provide new functionality.

    What is a Lightning Message Service?

    • LMS is defined as the standard publish-subscribe library that enables communication quickly and seamlessly with DOM across the Salesforce UI tech stack, including Visualforce Pages, Aura components, and Lightning Web Components (LWC) using simple API.
    • With this unique feature of Salesforce, you can publish messages and subscribe to them anywhere within the lightning page.
    • Lightning Message Service feature is similar to Aura application events that enable seamless communication between components.
    • Lightning Message Service is based on Lightning Message Channels, a new metadata type. 
    • Lightning Message Channel is used to access the Lightning Message Service API and Lightning Message Channel in LWC via scoped module @salesforce/messageChannel. When it comes to Visualforce, you can use the global variable $MessageChannel.
    • In Aura, you can use lightning:messageChannel in your component.

    Uses Of Lightning Message Service :

    • To enable communication between Visualforce page, Lightning web components, and Aura components, 
    • To access Lightning Message Service API for publishing messages throughout Lightning Experience.
    • It helps in subscribing to messages that originated from anywhere within Lightning Experience via Lightning Message Channel. 
    • A specific namespace is associated with Lightning Message Channel. Developers can choose whether they want their message channel to be available to other namespaces or not, ensuring the security of communication on Lightning Message Service.

    Lightning Message Channel :

    • It’s basically the name of Schema which will hold the actual message.
    • create file LMSDemoWin.messageChannel-meta.xml in folder messageChannels.

    <?xml version=”1.0″ encoding=”UTF-8″?>
    <LightningMessageChannel xmlns=”http://soap.sforce.com/2006/04/metadata”>
       <masterLabel>LMS Demo</masterLabel>
       <isExposed>true</isExposed>
       <description>Winter 20 – LMS Demo.</description> 
    </LightningMessageChannel>

    Deploy Lightning Message Channel :

    • Run below SFDX command to deploy this message channel on your Salesforce Org.
    • Run push command to deploy message channel on Orgs.
    • Once, Lightning Message Channel is created, let’s start by creating components and first we will create below Visualforce Page.

    <apex:page>
        <!– Begin Default Content REMOVE THIS –>
        <h1>Lightning Message Services – Demo – Winter 20</h1>
        <div>
            <p>Message To Send</p>
            <input type=”text” id=”vfMessage” />
            <button onclick=”publishMessage()”>Publish</button> 
            <br/> 
            <button onclick=”subscribeMC()”>Subscribe</button> 
            <button onclick=”unsubscribeMC()”>Unsubscribe</button> 
            <br/>
            <p>Messages Received:</p>
            <textarea id=”txtMessages” rows=”2″ style=” width:100%;” />
        </div>
        <script> 
            // Load the MessageChannel token in a variable
            var lmsDemoChannel = “{!$MessageChannel.LMSDemoWin__c}”;
            var subscriptionToMC;
           function publishMessage() {
                const payload = {
                    source: “Visualforce”,
                    messageBody: document.getElementById(‘vfMessage’).value
                };
                sforce.one.publish(lmsDemoChannel, payload);
            }
            function subscribeMC() {
                if (!subscriptionToMC) {
                    subscriptionToMC = sforce.one.subscribe(lmsDemoChannel, onMCPublished);
                }
            }
            function unsubscribeMC() {
                if (subscriptionToMC) {
                    sforce.one.unsubscribe(subscriptionToMC);
                    subscriptionToMC = null;
                }
            }
            function onMCPublished(message) {
                var textArea = document.querySelector(“#txtMessages”);
                textArea.innerHTML = message ? ‘Message: ‘ + message.messageBody + ‘ From: ‘ + message.source : ‘no message payload’;
            } 
        </script>
    </apex:page>
    • Next component we would build would be the Aura Component.

    <aura:component description=”testMessageAura” implements=”flexipage:availableForAllPageTypes” access=”global”>
        <aura:attribute type=”String” name=”myMessage”/>
        <aura:attribute type=”String” name=”receivedMessage”/>
        <lightning:messageChannel type=”LMSDemoWin__c” aura:id=”lmsDemohannel” onMessage=”{!c.handleReceiveMessage}”/>
        <lightning:card title=”Aura Component” iconName=”custom:custom18″>
            <div class=”slds-m-around_medium”>
                <lightning:input type=”text” value=”{!v.myMessage}” label=”Message To Send”/>
                <lightning:button label=”Publish” onclick=”{! c.handleClick}”/>
                <br/>
                <br/>
                <p>Latest Received Message</p>
                <lightning:formattedText value=”{!v.receivedMessage}”/>
            </div>
        </lightning:card>
    </aura:component>

    • Controller of Aura Component

    ({
        handleClick: function(component, event, helper) {
            let myMessage = component.get(“v.myMessage”);
            const payload = {
                source: “Aura Component”,
                messageBody: myMessage
            };
            component.find(“lmsDemohannel”).publish(payload);
        },
        handleReceiveMessage: function (component, event, helper) {
            if (event != null) {
                const message = event.getParam(‘messageBody’);
                const source = event.getParam(‘source’);
                component.set(“v.receivedMessage”, ‘Message: ‘ + message + ‘. Sent From: ‘ + source);
            }
        }
    });

    • Aura Component by default handles those operations once we declare them.
    • Last component we would be creating is the Lightning Web Component.

    <template>
        <lightning-card title=”LWC” icon-name=”custom:custom18″>
            <div class=”slds-m-around_medium”>
                <lightning-input label=”Message To Send” type=”text” value={_msg} onchange={handleChange}></lightning-input>
                <lightning-button label=”Publish” onclick={handleClick}></lightning-button>
                <br>
                <lightning-button label=”Subscribe” onclick={handleSubscribe}></lightning-button>
                <lightning-button label=”Unsubscribe” onclick={handleUnsubscribe}></lightning-button>
                <p> Message Received</p>
                <lightning-formatted-text value={receivedMessage}></lightning-formatted-text>
            </div>
        </lightning-card>
    </template>
    • Javascript of LWC

    import { LightningElement, track} from ‘lwc’;
    import { publish,createMessageContext,releaseMessageContext, subscribe, unsubscribe } from ‘lightning/messageService’;
    import lmsDemoMC from “@salesforce/messageChannel/LMSDemoWin__c”;
    export default class LMS_MessageSenderReceiverLWC extends LightningElement {
        @track _msg = ”;
        @track receivedMessage = ”;
        channel;
        context = createMessageContext();
        constructor() {
            super();
        }
        handleSubscribe() {
            const parentPage = this;
            this.channel = subscribe(this.context, lmsDemoMC, function (event){
                if (event != null) {
                    const message = event.messageBody;
                    const source = event.source;
                    parentPage.receivedMessage = ‘Message: ‘ + message + ‘. Sent From: ‘ + source;
                }
            });
        }
        handleUnsubscribe() {
            unsubscribe(this.channel);
        }
        handleChange(event) { 
            this._msg = event.target.value;
        }
        handleClick() {  
            const payload = {
                source: “Lightnign Web Component”,
                messageBody: this._msg
            }; 
            publish(this.context, lmsDemoMC, payload);
        } 
        disconnectedCallback() {
            releaseMessageContext(this.context);
        }
    }

    • Once we embed all three components (Visualforce, Aura and Lightning Web Components), we would be able to see Lightning Message Service in action as shown in below image.

    Advantage of Lightning Message Service :

    • One of the significant benefits is increased development time. For instance, if a Visualforce Page or Lightning component tries to reference a message channel that is non-available and that message channel is not exposed, then the code would not compile. 
    • This messaging service offers referential integrity between the code that references them and the message channel.
    • It restricts the deletion of message channels, which are referenced by other codes. Further, Lightning Message Service supports auto-adding message channels to packages.
    • As the metadata type is packageable, you can associate a message channel to a particular namespace and make it available/unavailable to other namespaces.
  • Convert DateTime of one timezone to datetime of another Timezone

    Time zones in Salesforce:-

    Time zones come in two varieties — region-based and offset-based. In Salesforce, we see region-based time zones very often. 

    If you go to your Company Information page on setup, you would see a list of time zones. For example America/Chicago and America/Los_Angeles. The list of region-based time zones available in Apex is given in an article. Here is the complete list of supported timezones in salesforce. Apex supports all time zones returned by the TimeZone.getAvailableIDs method of the TimeZone class.

     

    TimeZone Class:-

    Represents a time zone. Contains methods for creating a new time zone and obtaining time zone properties, such as the time zone ID, offset, and display name

    You can use the methods in this class to get properties of a time zone, such as the properties of the time zone returned by UserInfo.getTimeZone, or the time zone returned by getTimeZone of this class.

     

    Example :-

    TimeZone tz = UserInfo.getTimeZone();
    System.debug('Display name: ' + tz.getDisplayName());
    System.debug('ID: ' + tz.getID());
    // During daylight saving time for the America/Los_Angeles time zone
    System.debug('Offset: ' + tz.getOffset(DateTime.newInstance(2012,10,23,12,0,0)));
    // Not during daylight saving time for the America/Los_Angeles time zone
    System.debug('Offset: ' + tz.getOffset(DateTime.newInstance(2012,11,23,12,0,0)));
    System.debug('String format: ' + tz.toString());
     

    Datetime class:-

    Datetime means a value that indicates a particular day and time, such as a timestamp. You can add or subtract an Integer or Double value from a Datetime value, returning a Date value. Addition and subtraction of Integer and Double values are the only arithmetic functions that work with Datetime values. You can’t perform arithmetic functions that include two or more Datetime values. Instead, use the Datetime methods.

     

    For example :-

    datetime myDateTime = datetime.now();</p>
    DateTime dt = DateTime.newInstance(2012, 1, 26, 5, 2, 4);
    System.assertEquals(2012, dt.year());
     

    So let’s use below code to convert time in different timezone

    public class ConvertTimeZoneService{
        
        public static string EST='America/New_York';
        ///Convert Any time to other timezone
        public Time convertDateTimeToOtherTimeZone(DateTime dttime, string sourceTimezone, string targetTimezone)
        {
            TimeZone tz = Timezone.getTimeZone(sourceTimezone);
            System.debug('Display name: ' + tz.getDisplayName());
            System.debug('ID: ' + tz.getID());
            
            Integer offset=tz.getOffset(dttime);
            System.debug('Offset: ' + offset);
            
            // target Timezone.
            TimeZone targetTZ = Timezone.getTimeZone(targetTimezone);
            System.debug('Display name: ' + targetTZ.getDisplayName());
            integer offsetTotargetTZ = targetTZ.getOffset(dttime);
           	integer correction = offsetTotargetTZ- offset;
        
            DateTime targetDT = dttime.addMinutes(correction / (1000 * 60));
            
            return Time.newInstance(targetDT.hour(), targetDT.minute(), targetDT.second(), targetDT.millisecond());
        }
    }
    
     

    1. Convert Datetime to another Timezone:-

    So to convert DateTime to another timezone we can use the above ConvertTimeZoneService class method.

    DateTime dtTime = DateTime.now();
    DateTime dtTimeTimeZone = new ConvertTimeZoneService().convertDateTimeToOtherTimeZone(dtTime, 'America/Santiago','America/New_York');
    
     

    So by using the convertDateTimeToOtherTimeZone method we can convert any DateTime to another timezone.

     

    2. Convert Time to another Timezone

    To convert Time to another TimeZone we can use the ConvertTimeZoneService class method by passing the DateTime value to that method which we want to convert.

    Date dt = Date.today();
    Time tm = acct.TimeToCall__c; //Here we can use any field which contains time
    DateTime dtTime = DateTime.newInstance(dt.year(),dt.month(),dt.day(),tm.hour(),tm.minute(),tm.second());
    DateTime dtTimeTimeZone = new ConvertTimeZoneService().convertDateTimeToOtherTimeZone(dtTime, 'America/Santiago','America/New_York');
    
  • Introduction to Surveys in Salesforce : Every business small or big wants to satisfy its customers’ needs since customers are the lifeblood of any business. If you do not know what customers think about your service, you will never be able to give them the best customer experience. so any contact with a customer is […]

    Read More

  • Text Rich Area Field In Flow

    Rich Text fields provide important functionality but can be difficult to employ and deal with properly, especially in Flows. In this blog post, we will see how we can use a Lightning web component to act as a rich text area.

    What is a Rich Text Area Field? 

    • Rich Text is a field type that enables authors to create rich text content.
    • The Rich Text field provides rich formatting options for text entered into its field.
    • The text formatting options are presented in a toolbar which is displayed on top of the field.
    • Rich Text field type is mostly used when users need to apply various formatting options to their data, like changing the font, to enter html, to enter bulleted points and many other such options.
    • This field type accepts all kinds of data, for example, plain text, special characters, numbers.

    Limitations, when working with Rich Text Area Fields.

    • Salesforce supports up to 131,072 characters for each rich text area field, including the HTML tags.
    • An object can contain unlimited rich text area and long text area fields, although your edition’s allocation for total custom fields allowed on an object, regardless of field type, applies.
    • Each object can contain 1,638,400 characters across long text area and rich text area fields.
    • When you create a long text area or rich text area field, you set a character limit for the field—the maximum length of the text that can be entered.
    • You can’t paste special characters, such as bullets or curly quotes, into a rich text field from another application. It’s best to type or paste in plain text and use the rich text editor to format it.
    • HTML code isn’t supported in the Salesforce HTML editor. HTML code is treated as text.
    • The character count includes HTML markup that is not visible in the editor. The HTML markup is returned through the API.
    • Depending on how much formatting you apply, the number of characters you can type into the rich text field is fewer than the specified limit. This is because the HTML markup counts against the character limit of a field. For example, bold formatting includes the <b></b> tag around your text and adds up to 7 more characters.
    • Special characters like & are encoded as &amp; which adds up to 5 more characters. Also, the rich text field in Lightning Experience and Salesforce Classic can vary in HTML markup, such as with using RGB or hexadecimal values when color formatting is applied. Paragraph and line breaks also insert the <p></p> and <br> tags, counting against the character limit. See Editing Rich Text Area Fields in Records for information on formatting support.

    Steps To Add Text Rich Area Field In Flow?

    • Create a LWC component and name it TextAreaFlow.
    • You will get the complete code from Here.
    • To execute the flow action and for flow support we need to import some actions from the lightning/flowSupport library.

    import { FlowAttributeChangeEvent, FlowNavigationNextEvent, FlowNavigationFinishEvent, FlowNavigationBackEvent, FlowNavigationPauseEvent } from ‘lightning/flowSupport’;

    Configure Component in Flow

    • Create a flow or edit the flow where you wanted to use the rich text area field.
    • Drag & Drop the LWC inside the Screen element.

    Advantage of using Rich Text Area Field

    1. The Rich text field lets you add any kind of static text, image and others.
    2. There are multiple formatting options such as
    • Bold
    • Italics
    • Underline
    • Strikethrough
    • Text color
    • Alignment
    • Headings
    • Hyperlinks
    • Bullets
    • Blockquote
    • Add an image
  • Fault Path In Salesforce Flow

    Introduction to Salesforce Flow

    • Salesforce Flow empowers you to build complex business solutions using clicks, not code.
    • Flow Builder is the most powerful tool that a Salesforce Admin has at their disposal, giving you similar powers that Salesforce developers have.
    • If you need to perform mass updates across multiple unrelated records, or complex logic into opportunity conversion, these are common examples for when you should use Flow.
    • The use cases for Flow are endless, and its capabilities are growing with every Salesforce release.
    • Formerly Visual Flow, Salesforce Flow has gone through significant upgrades to give us the Flow Builder interface, after being completely rebuilt from the ground up.

    What are Salesforce Flows?

    • Flows allow you to build complex business automation using clicks instead of code. As an admin, Flows are going to be your best friend because you will be able to handle the majority of complex business requirements without the help of a Salesforce developer.
    • The benefit of Salesforce Flow is that they are easy to maintain because anyone (assuming they know Flows) should be able to follow along with what you built.
    • Flows are accessible through the Setup menu. Simply enter ‘Flows’ into the Quick Find box, and create a new Flow to get started

    What Happens When a Flow Fails?

    • When you’re deciding whether to customize the error handling in your flow, consider how a failed flow behaves.
    • When a flow fails, the user running the flow gets this error message.

    An unhandled fault has occurred in this flow
    An unhandled fault has occurred while processing
    the flow. Please contact your system administrator
    for more information.

    • The running user can’t proceed with the flow or return to a previous part of the flow. The admin who created the flow receives a faulty email.
    • The email details the element that failed, the error message from that element, and which elements were executed during the failed interview.
    • Here’s an example error message.

    An error occurred at element Delete_1.
    DELETE — There is nothing in Salesforce matching your
    delete criteria.

    The Fault Connector :

    • Most readers have seen the ‘Unhandled Fault’ message.
    • Wonder how many of you have seen ‘Fault Connectors’ which Salesforce provides to handle Flow errors.
    • They are recommended as best practice and using them can make flows failing a lot less stressful.
    • Can use the fault connector from any of the ‘data’ elements , or the Action elements in the Flow toolbox.

    How to Create a fault connector :

    • Simply create a second connection from your element after creating your first connection.
    • We now know how to create a fault connection, but what do we attach it to? Below is a simple screen flow which lets users create a Contact and Account at the same time.

    Where did the flow fail?

    • Use an assignment element to record exactly where the flow went wrong. Assign a value to a text variable called ‘Error location’.

    Advantage of adding Fault Path In Salesforce Flow :

    • Never see that red ‘Unhandled Fault’ message on your screen again.
    • Use a Screen element and Display Text to communicate with the user.
    • You can even add images and merge fields such as {!$Flow.FaultMessage}.
    • With this fault message, the user might even be able to see what is wrong themselves.