Passing objects to future methods

Future methods are used to run a code in a separate thread at a later time when system resources are available. We can use them to run something asynchronously, for example make a web service callout from an Apex Trigger. This way we can make sure user does not wait for response to get back. Future methods must be static and if you want to make callouts annotation needs to include (callout=true):

<pre class="wp-block-syntaxhighlighter-code">
@future (callout=true)
public static void doCallout() {
    //make callout here
}
</pre>

Future methods does not allow passing objects as an arguments, only primitive data types are accepted, however we can oversome this limitation by using serialization and deserialization. Here is how we can do this:

OpportunityTrigger

<pre class="wp-block-syntaxhighlighter-code">
Trigger OpportunityTrigger on Opportunity( after insert) {
     String jsonString = json.serialize(Trigger.NEW);

     OpportunityTriggerHandler.process(jsonString);
}
</pre>

OpportunityTriggerHandler

<pre class="wp-block-syntaxhighlighter-code">
public class OpportunityTriggerHandler {
    @future(callout=true)
    public static void process( String jsonString) {
          List&amp;lt;Opportunity&gt; oppNewtList = (List&amp;lt;Opportunity&gt;)Json.deserialize(jsonString, List&amp;lt;Opportunity&gt;.class);
    }
}
</pre>

Add Dropdown (Picklist) in Lightning Web Component.

In Aura Components we can use lightning-select to create dropdown. In Lightning Web Component there is a lightning-combobox component that allows to do this.

Here is example on how to do this in LWC:

LightningDropDown.html

LightningDropDown.js

import { LightningElement, track } from 'lwc';

export default class LightningDropDown extends LightningElement {
@track selectedColor = 'white';

get colorOptions() {
    return [
             { label: 'White', value: 'white' },     
             { label: 'Red', value: 'red' },
             { label: 'Green', value: 'green' },
             { label: 'Blue', value: 'blue' },
           ];
}

handleChange(event) {
        this.selectedColor = event.detail.value;
     }
}

How to show toast notification in Lightning Web Component example.

Let’s talk about toast notification pop ups in Salesforce Lightning. Toast notification can pop up and display error, warning, success or information messages. The style of the notification depends on the variant of the toast. You don’t have to set variant of the toast – default value is info. To use toast in Lightning Web Component you need to import ShowToastEvent from the lightning/platformShowToastEvent module.

import { ShowToastEvent } from 'lightning/platformShowToastEvent'

Javascript Controller:

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent'

export default class ShowToastDemo extends LightningElement {
    showInfoToast() {
        this.showToast( 'Info Title', 'Info Message', 'info' );
    }
    showSuccessToast() {
        this.showToast( 'Success Title', 'Success Message', 'success' );
    }
    showWarningToast() {
        this.showToast( 'Warning Title', 'Warning Message', 'warning' );
    }
    showErrorToast() {
        this.showToast( 'Error Title', 'Error Message', 'error' );
    }

    showToast( title, message, variantStr ) {
        const event = new ShowToastEvent({
            title: title,
            message: message,
            variant: variantStr
        });
        this.dispatchEvent(event);
    }
}

In our demo lightning web component we will add 4 buttons – one for each variant of toast notification:

Info Toast Notification:

Success Toast Notification:

Warning Toast Notification:

Error Toast Notification:

Basic differences between Aura Component and Lightning Web Components in HTML

Lightning Web Components is an implementation of the W3C’s Web Components standards.The Aura Component framework is a UI framework for developing web apps for mobile and desktop devices. It’s a modern framework for building single-page applications with dynamic, responsive user interfaces for Lightning Platform apps. It uses JavaScript on the client side and Apex on the server side.

Aura components can contain Lightning web components but Lightning web components can’t contain Aura components.

When you create an Aura component , it has the following files:
example.cmp, exampleController.js, exampleHelper.js, exampleRenderer.js, example.css and a configuration file.
When you create a Lightning web component, it has the following files:
example.html, example.js, example.css and a configuration file

Here are the basic differences in HTMl between Aura and LWC:

  • An Aura component contains markup in a .cmp file. The file starts with an <aura:component> tag and can contain HTML and Aura-specific tags.A Lightning web component contains markup in a .html file.
  • The file starts with a <template> tag and can contain HTML and directives for dynamic content.
  • In Aura component the attributes are defined in <aura:attribute> tag. While in Lightning web component it is defined as JS properties.
  • Syntax for Dynamic component in Aura is {!v.count}, while in Lightning web component it is {count}. You don’t need the ‘!’ and the ‘v.’ .
  • Conditional markup changes from :
    <aura:if isTrue=”{!v.showsection}”>
        to
    <template if:true={showsection}></template>
    ( Please notice that there is no quotes around the dynamic content. This is true through out the LWC. )
  • In Aura you can do additional conditions in your expression language. In LWC, you will have to move this condition to JS. For example in Aura to check for a condition if the count is 1 , you can add it in the <aura:if> for example:
              <aura:if isTrue=”{!v.count > 1}”>
                          //show content
             </aura:if>

    While in lwc we have to move this logic to JS and use the variable in the expression language:
    HTML will look like this in LWC :

                 <template if:true={hasMoreThanOne}>
                           //show content
                 </template>

    JS will look like this:
                import { LightningElement, api } from ‘lwc’;
                export default class Paginator extends LightningElement {
                        @api count;
                         get hasMoreThanOne() {
                               return this.count === 1;
                         }
                 }

  • In Aura for Iterations we use <aura:iteration>, then use the ‘items’ attribute to pass the collection and ‘var’ attribute to pick the individual item from the collections. In LWC we can use ‘for:each’ and ‘for:item’ for passing collections and individual variable accordingly.
    Aura:
             <aura:iteration items=”{!v.properties}” var=”property”>
                    // show the data associated with each property
             </aura:iteration>
    LWC:
            <template for:each={properties.data.records}  for:item=”property”>
                   //show content
             </template>
  • We use the init handler in Aura to run code that we need to run before rendering an Aura component. In LWC we replace this with connectedCallback() lifecycle hook. There are multiple lifecycle hooks that you can use to run code at different stages of the component’s lifecycle.
  •  Self closing tags are not allowed in LWC, while they are allowed in Aura.
  • Aura CSS can be converted LWC CSS by removing ‘.THIS’
    To convert the Base Lightning components from Aura to LWC syntax, we can follow these points:
              * Change the colon that separates the namespace (lightning) and  component name (formattedNumber) to a dash.
              * Change the camel-case component name (formattedNumber) to a dash-separated name (formatted-number).
              * Change the camel-case attribute name (currencyCode) to a dash-separated name (currency-code).
    This will convert a lightning base component in Aura
         <lightning:formattedNumber/>
                             to
        <lightning-formatted-number></<lightning-formatted-number>

Adding Merge Duplicate Accounts tool in Lightning Experience like in classic.

Salesforce added Duplicate Rules and Lightning Experience is missing Merge Accounts and Contacts in tools. If you would like to the merge tool just like in classic. You can add custom button to list views. Here is how you can do it:

  1. Create a custom button. Display Type – List Button, Content Source: URL and use this URLs :

/merge/accmergewizard.jsp?retURL=/001

2. Add button to the List View Search Layout.

To add button navigate to Object Manager => Account => Search Layouts for Salesforce Classic.

Edit List View layout and add Merge Accounts button.

Now if you you go to any Account List view you will see Merge Accounts button.

Adding users to permission set through Apex

Here is how we can add/remove a user to/from a permission set through Apex. My requirement was to add or remove a user from a permission set when the value of a checkbox changes in user object.So I have this code in User Update After trigger.

Here is the code to add to a PermissionSet:

Here is the code to remove from a PermissionSet:

 

Lightning Web Component in Utility Bar example

Here I will show how to make lightning web component available to be used as Utility Bar Item.

First create new Lightning Web Component.

sfdx force:lightning:component:create --type lwc --componentname UtilityBarExample --outputdir force-app\main\default\lwc

Open meta configuration XML file utilityBarExample.js-meta.xml and change it – add targets lightning__UtilityBar and lightning__AppPage and change
isExposed to true, so the file looks like this:

Create Scratch org if you don’t have one (quick command that uses default config and 30 duration day for Scratch org):

sfdx force:org:create -f config\project-scratch-def.json --setalias LightningWebComponents --durationdays 30 --setdefaultusername --json --loglevel fatal

Push code to your scratch org:

sfdx force:source:push --json --loglevel fatal

Go to Setup –> Apps –> App Manager.

Select the app that you want to add Utility Item to and select Edit. Then go to Utility Items and add Utility Item.


You should be able to see your custom component in the list of available components.Now you can add this Lightning Web Component in Utility Bar.

Lightning Web Component Datatable example with sorting and search functionality.

Many people are familiar with lightning datatable component and how to use it in Aura Component. In this article I want to show example how to use lightning component in Lightning Web Component and build simple search by name and column sorting.

First we need to create an apex class.

You can create it either in Salesforce UI or Developer Console or do it in Visual Studio Code with SFDX command:

sfdx force:apex:class:create --classname GetAccounts --template DefaultApexClass --outputdir force-app\main\default\classes

Code for Apex class:

Second we will need to create Lightning Web Component budle.

sfdx force:lightning:component:create --type lwc -n LightningDatatableExample -d force-app/main/default/lwc

Code for html component:

JS controller:

To make sure component is visible in Lightning App Builder you need to add targets and change isExposed to true in LightningDatatableExample.js-meta.xml file:

How to clear selected rows in Lightning DataTable?

I have a lightning datatable where I am displaying leads.

Once I selected the rows that I wanted and completed the action, I noticed that the checkboxes are not getting unchecked.

Here is what I added to the action method to make sure that the checkboxes will be unchecked after the action is completed.

Hope it helps 🙂

How to create Popup Using Lightning Web Components?

Lightning Web Components is the new programming model that you can use to build Lightning components in Salesforce. Here Is how you can create a Popup in Salesforce using LWC.

The following is the JavaScript that foes in the filename.js

import { LightningElement , track } from 'lwc';

export default class PopUpExample extends LightningElement {
    @track openModal;
    openPopUp() {
        this.openModal = true;
    }
    closePopUp() {
        this.openModal = false;
    }
    saveAction(){
        // eslint-disable-next-line no-console
        console.log( 'saveaction is called');
        this.closePopUp();
    }
}

Here is the xml file

When you create a new lwc, make sure the isExposed is updated to True in the xml file. The default is false, the component will not show up in the Lightning Builder even if you deploy the component to your org. Also update the <targets> based on what your requirements are.

That’s it.. Hope it helps.