Future Methods in Salesforce

Future Methods in Salesforce @future

Future Methods in Salesforce using @future annotation

A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time. You can also use future methods to isolate DML operations on different sObject types to prevent the mixed DML error. Each future method is queued and executes when system resources become available. That way, the execution of your code doesn’t have to wait for the completion of a long-running operation. A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits.

Future Methods in Salesforce

Future method syntax

global class FutureClass {
    @future
    public static void myFutureMethod() {   
         // Perform some operations
    }
}
  • Use @future annotation before the method declaration.
  • Future methods must be static methods, and can only return a void type.
  • The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types.
  • Future methods can’t take standard or custom objects as arguments.
  • A common pattern is to pass the method a list of record IDs that you want to process asynchronously.
    global class FutureMethodRecordProcessing {
        @future
        public static void processRecords(List<ID> recordIds){   
    	// Get those records based on the IDs
    	List<Account> accts = [SELECT Name FROM Account WHERE Id IN :recordIds];
    	// Process records
        }
    }
    

Future method callouts using @future(callout=true)

To allow callout from the future method annotation needs an extra parameter (callout=true) to indicate that callouts are allowed. Here is example

global class FutureMethodExample {
    @future(callout=true)
    public static void getStockQuotes(String acctName){
    	// Perform a callout to an external service
    }
}

Test Class for Future Methods

To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously.

@isTest
private class MixedDMLFutureTest {
    @isTest static void test1() {
        User thisUser = [SELECT Id FROM User WHERE Id = :UserInfo.getUserId()];
       // System.runAs() allows mixed DML operations in test context
        System.runAs(thisUser) {
            // startTest/stopTest block to run future method synchronously
            Test.startTest();        
            MixedDMLFuture.useFutureMethod();
            Test.stopTest();
        }
        // The future method will run after Test.stopTest();
    
        // Verify account is inserted
        Account[] accts = [SELECT Id from Account WHERE Name='Acme'];
        System.assertEquals(1, accts.size());
        // Verify user is inserted
        User[] users = [SELECT Id from User where username='mruiz@awcomputing.com'];
        System.assertEquals(1, users.size());
    }
}

Future Method Performance Best Practices

Salesforce uses a queue-based framework to handle asynchronous processes from such sources as future methods and batch Apex. This queue is used to balance request workload across organizations. Use the following best practices to ensure your organization is efficiently using the queue for your asynchronous processes.

  • Avoid adding large numbers of future methods to the asynchronous queue, if possible. If more than 2,000 unprocessed requests from a single organization are in the queue, any additional requests from the same organization will be delayed while the queue handles requests from other organizations.
  • Ensure that future methods execute as fast as possible. To ensure fast execution of batch jobs, minimize Web service callout times and tune queries used in your future methods. The longer the future method executes, the more likely other queued requests are delayed when there are a large number of requests in the queue.
  • Test your future methods at scale. Where possible, test using an environment that generates the maximum number of future methods you’d expect to handle. This helps determine if delays will occur.
  • Consider using batch Apex instead of future methods to process large numbers of records.

 

For more details please refer to official link

To define a future method, simply annotate it with the future annotation, as follows.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/future-methods-in-salesforce/

Introducing Playground – Share and Collaborate Salesforce Solutions

Introducing Playground – Share and Collaborate Salesforce Solutions

 

  • Are you a Salesforce developer or an administrator working on a development task?
  • Did you just spend writing a block of code again that you wrote a while ago?
  • Can’t recall where you last saw a similar solution that you’re implementing?
  • Have you hit a blocker while writing your code in apex or lightning?

Your best bet – google it! But can you always find what you’re looking for? Say even if you do, is it time consuming for you to clean it up and bring back to use?

If all you could think of was a YES, then look no further and get ready to play!

Welcome to the Playground – an intuitive, collaborative and easy-to-use cloud application to upload and share solutions within the Salesforce ecosystem.

Playg icon

Playground is truly remarkable in making it super easy for developers to store their reusable code, to share it to the wider community and from having visitors search for an available solution to even letting them directly use it within their salesforce org with just a single click, oh yeah…that’s right – just one simple click. Now that’s called a power play!

We have an ever-increasing list of 49 amazing plays, fab five-some contributors and nearly 170 users with us already. Looking at the spectacular response, we are hopeful to be supporting the salesforce ecosystem even more. 

Playg statistics

Playground is built with an aim to “Reuse & Collaborate More”. With that in mind, here are top highlights of this app:

  • Designed specifically for Salesforce
  • Effective storage & organization of reusable assets at one place
  • Powerful search to find the right solution at the right time
  • Hassle free one-click deployments, straight into any Salesforce org
  • Insights to track the progress of any solution
  • Tracker to know how well a solution is accepted by the community

 

As echoed above, we wanted to build a one stop shop for all our fellow Salesforce users out there to store any reusable components and collaborate for a progressive future together.

Finally, it’s time to hit the playground and have some fun!

 

Thank you,

Team Playg

Permanent link to this article: https://www.sfdcpoint.com/salesforce/introducing-playground-share-and-collaborate-salesforce-solutions/

template if:true Conditional Rendering LWC

template if:true Conditional Rendering LWC

template if:true Conditional Rendering LWC(Lightning Web Component)

To render HTML conditionally, add the if:true|false directive to a nested <template> tag that encloses the conditional content. template if:true|false directive is used to display conditional data.

Render DOM Elements Conditionally Lightning Web Component

The if:true|false={property} directive binds data to the template and removes and inserts DOM elements based on whether the data is a truthy or falsy value.

 

template if:true  LWC Example

Let’s see a simple example to show content based on the selection of checkbox. Example contains a checkbox labeled Show details. When a user selects or deselects the checkbox., based on that content is visible. This example has been copied from official link.

templateIFTrueExampleLWC.html

<template>
    <lightning-card title="TemplateIFTrueConditionalRendering" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <lightning-input type="checkbox" label="Show details" onchange={handleChange}></lightning-input>
            <template if:true={areDetailsVisible}>
                <div class="slds-m-vertical_medium">
                    These are the details!
                </div>
            </template>
        </div>
    </lightning-card>
</template>

templateIFTrueExampleLWC.js

import { LightningElement } from 'lwc';
export default class TemplateIFTrueExampleLWC extends LightningElement {
    areDetailsVisible = false;
    handleChange(event) {
        this.areDetailsVisible = event.target.checked;
    }
}

templateIFTrueExampleLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this lwc component on home page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your templateIFTrueExampleLWC component and drag it on right hand side top.
  • Click Save and activate.

 

We will get the following Output

template if true Conditional Rendering LWC

 

When user select the checkbox, we will see the following output

template if true Conditional Rendering LWC selected

 

Let’s see some practical example. In this example, account list is fetched from the database. If there is some error in fetching account list then show error otherwise show account list

AccountHelper.cls

public with sharing class AccountHelper {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Type, Rating,
                Phone, Website, AnnualRevenue
            FROM Account];
    }
}

accountListForEachLWC.html

<template>
    <lightning-card title="Account List using for:each" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <template if:true={accounts.data}>
                <template for:each={accounts.data} for:item="acc">
                    <p key={acc.Id}>{acc.Name}</p>
                </template>
            </template>
            <template if:true={accounts.error}>
                {accounts.error}
            </template>
        </div>
    </lightning-card>
</template>

accountListForEachLWC.js

import { LightningElement, wire } from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
export default class AccountListForEachLWC extends LightningElement {
    @wire(getAccountList) accounts;
}

For full detail about this example, please refer to for:each template directives in LWC

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/template-iftrue-conditional-rendering-lwc/

lightning:recordForm Example

lightning:recordForm Example

lightning:recordForm Example lightning aura component

lightning:recordForm component allows you to quickly create forms to add, view, or update a record. Using this component to create record forms is easier than building forms manually with lightning:recordEditForm or lightning:recordViewForm. The lightning:recordForm component provides these helpful features:

  • Switches between view and edit modes automatically when the user begins editing a field in a view form
  • Provides default Cancel and Save buttons in edit forms
  • Uses the object’s default record layout with support for multiple columns
  • Loads all fields in the object’s compact or full layout, or only the fields you specify

 

lightning:recordForm is less customizable. To customize the form layout or provide custom rendering of record data, use lightning:recordEditForm (add or update a record) and lightning:recordViewForm (view a record).

The objectApiName attribute is always required, and the recordId is required only when you’re editing or viewing a record.

lightning:recordForm implements Lightning Data Service and doesn’t require additional Apex controllers to create or edit record data. It also takes care of field-level security and sharing for you, so users see only the data that they have access to.

Modes

The component accepts a mode value that determines the user interaction allowed for the form. The value for mode can be one of the following:

  • edit – Creates an editable form to add a record or update an existing one. When updating an existing record, specify the record-id. Edit mode is the default when record-id is not provided, and displays a form to create new records.
  • view – Creates a form to display a record that the user can also edit. The record fields each have an edit button. View mode is the default when recordId is provided.
  • readonly – Creates a form to display a record without enabling edits. The form doesn’t display any buttons.

 

Specifying Record Fields

For all modes, the component expects the fields attribute or the layoutType attribute.

Use the fields attribute to pass record fields as an array of strings. The fields display in the order you list them.

Use the layoutType attribute to specify a Full or Compact layout. Layouts are typically defined (created and modified) by administrators. Specifying record data using layout-type loads the fields in the layout definition. All fields that have been assigned to the layout are loaded into the form.

To see the fields in the layout types in your org:

  • Full – The full layout corresponds to the fields on the record detail page. From the management settings for the object that you want to edit, go to Page Layouts.
  • Compact – The compact layout corresponds to the fields on the highlights panel at the top of the record. From the management settings for the object that you want to edit, go to Compact Layouts.

 

Editing a Record using lightning:recordForm

lightningRecordFormEditExampleAura.cmp

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId">
    <aura:attribute name="fields" type="String[]" default="['Name','AnnualRevenue','Industry']" />
    <lightning:recordForm aura:id="myRecordForm" recordId="{!v.recordId}" objectApiName="Account" fields="{!v.fields}" columns="2" mode="edit" onsubmit="{!c.handleSubmit}" />
</aura:component>

lightningRecordFormEditExampleAuraController.js

({
    handleSubmit : function(cmp, event, helper) {
        
        //you can change values from here
        /*const fields = event.getParam('fields');
        fields.Name = 'My Custom Name'; // modify a field
        cmp.find('myRecordForm').submit(fields);*/
    }

Now we can add this lightning aura component on the Account Record page.

  • Go to Account record
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your lightningRecordFormEditExampleAura component and drag it on Accont page.
  • Click Save and activate.

 

We will get the following output

lightningrecordForm Example Edit Record

 

Creating a Record using lightning:recordForm

lightningRecordFormEditExampleAura.cmp

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
            <aura:attribute name="fields" type="String[]" default="['Name','AnnualRevenue','Industry']" />
            <aura:attribute name="recordId" type="String"/>
            <lightning:notificationsLibrary aura:id="notifLib"/>
            <lightning:recordForm objectApiName="Account" fields="{!v.fields}" onsuccess="{!c.handleSuccess}" />
</aura:component>

lightningRecordFormCreateExampleAuraController.js

({
    handleSuccess : function(component, event, helper) {
        component.find('notifLib').showToast({
            "variant": "success",
            "title": "Account Created",
            "message": "Record ID: " + event.getParam("id")
        });
    }
})

Now we can add this lightning aura component on the Account Record page.

  • Go to Account record
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your lightningRecordFormCreateExampleAura component and drag it on Accont page.
  • Click Save and activate.

 

We will get the following output

lightningrecordForm Example Create Record

 

For more details please refer to official link

Permanent link to this article: https://www.sfdcpoint.com/salesforce/lightningrecordform-example/

lightning-record-form LWC

lightning-record-form LWC (Lightning Web Component)

lightning-record-form LWC

lightning-record-form component allows you to quickly create forms to add, view, or update a record. Using this component to create record forms is easier than building forms manually with lightning-record-edit-form or lightning-record-view-form. The lightning-record-form component provides these helpful features:

  • Switches between view and edit modes automatically when the user begins editing a field in a view form
  • Provides Cancel and Save buttons automatically in edit forms
  • Uses the object’s default record layout with support for multiple columns
  • Loads all fields in the object’s compact or full layout, or only the fields you specify

 

lightning-record-form is less customizable. To customize the form layout or provide custom rendering of record data, use lightning-record-edit-form (add or update a record) and lightning-record-view-form (view a record).

The object-api-name attribute is always required, and the record-id is required only when you’re editing or viewing a record.

lightning-record-form implements Lightning Data Service and doesn’t require additional Apex controllers to create or edit record data. It also takes care of field-level security and sharing for you, so users see only the data that they have access to.

 

Modes

The component accepts a mode value that determines the user interaction allowed for the form. The value for mode can be one of the following:

  • edit – Creates an editable form to add a record or update an existing one. When updating an existing record, specify the record-id. Edit mode is the default when record-id is not provided, and displays a form to create new records.
  • view – Creates a form to display a record that the user can also edit. The record fields each have an edit button. View mode is the default when record-id is provided.
  • readonly – Creates a form to display a record without enabling edits. The form doesn’t display any buttons.

 

Specifying Record Fields

For all modes, the component expects the fields attribute or the layout-type attribute.

Use the fields attribute to pass record fields as an array of strings. The fields display in the order you list them.

Use the layout-type attribute to specify a Full or Compact layout. Layouts are typically defined (created and modified) by administrators. Specifying record data using layout-type loads the fields in the layout definition. All fields that have been assigned to the layout are loaded into the form.

To see the fields in the layout types in your org:

  • Full – The full layout corresponds to the fields on the record detail page. From the management settings for the object that you want to edit, go to Page Layouts.
  • Compact – The compact layout corresponds to the fields on the highlights panel at the top of the record. From the management settings for the object that you want to edit, go to Compact Layouts.

 

Editing a Record using lightning-record-form LWC

lightningRecordFormEditExampleLWC.html

<template>
    <lightning-record-form record-id={recordId} object-api-name={objectApiName}
        fields={fields} columns="2" mode="edit" onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

lightningRecordFormEditExampleLWC.js

import { LightningElement, api } from 'lwc';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import REVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class LightningRecordFormEditExampleLWC extends LightningElement {
    @api recordId;
    @api objectApiName;
    fields = [NAME_FIELD, REVENUE_FIELD, INDUSTRY_FIELD];
    handleSubmit(event){
        //you can change values from here
        //const fields = event.detail.fields;
        //fields.Name = 'My Custom  Name'; // modify a field
        console.log('Account detail : ',event.detail.fields);
        console.log('Account name : ',event.detail.fields.Name);
    }
}

lightningRecordFormEditExampleLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this LWC component on the Account Record page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your lightningRecordFormEditExampleLWC component and drag it on right-hand side top.
  • Click Save and activate.

 

We will get the following output

lightning-record-form LWC Edit Record

 

We can change html file to show full page layout

lightningRecordFormEditExampleLWC.html

<template>
    <lightning-record-form record-id={recordId} object-api-name="Account" layout-type="Full" columns="2" mode="edit"
       onsuccess={handleSuccess} onsubmit={handleSubmit}>
    </lightning-record-form>
</template>

 

Creating a Record using lightning-record-form LWC

lightningRecordFormCreateExampleLWC.html

<template>
    <lightning-record-form object-api-name={objectApiName}
        fields={fields} onsuccess={handleSuccess}>
    </lightning-record-form>
</template>

lightningRecordFormCreateExampleLWC.js

import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import REVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
export default class LightningRecordFormCreateExampleLWC extends LightningElement {
    // objectApiName is "Account" when this component is placed on an account record page
    @api objectApiName;
    fields = [NAME_FIELD, REVENUE_FIELD, INDUSTRY_FIELD];
    handleSuccess(event) {
        const evt = new ShowToastEvent({
            title: "Account created",
            message: "Record ID: " + event.detail.id,
            variant: "success"
        });
        this.dispatchEvent(evt);
    }
}

lightningRecordFormCreateExampleLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this LWC component on the Account Record page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your lightningRecordFormCreateExampleLWC component and drag it on right-hand side top.
  • Click Save and activate.

 

We will get the following output

lightning-record-form LWC Create Record

For more details please refer to official link

Permanent link to this article: https://www.sfdcpoint.com/salesforce/lightning-record-form-lwc/

lightning-record-edit-form LWC(Lightning Web Component)

lightning-record-edit-form LWC

lightning-record-edit-form LWC (Lightning Web Component)

A lightning-record-edit-form component is a wrapper component that accepts a record ID and object name. It is used to add a Salesforce record or update fields in an existing record. The component displays fields with their labels and the current values and enables you to edit their values. The lightning-input-field component is used inside the lightning-record-edit-form to create editable fields. The lightning-output-field component and other display components such as lightning-formatted-name can be used to display read-only information in your form. lightning-record-edit-form implements Lightning Data Service. It doesn’t require additional Apex controllers to create or update records. Using lightning-record-edit-form to create or update records with Apex controllers can lead to unexpected behaviors. This component also takes care of field-level security and sharing for you, so users see only the data they have access to.

lightning-record-edit-form supports the following features:

  • Editing a record’s specified fields, given the record ID.
  • Creating a record using specified fields.
  • Customizing the form layout
  • Custom rendering of record data

 

Editing a Record

To enable record editing, pass in the ID of the record and the corresponding object API name to be edited. Specify the fields you want to include in the record edit layout using lightning-input-field.

Include a lightning-button component with type=”submit” to automatically save any changes in the input fields when the button is clicked.

Let’s create an example to edit account record using lightning-record-edit-form in Lightning Web Component

recordEditFormEditExampleLWC.html

<template>
    <lightning-record-edit-form record-id={recordId} object-api-name="Contact" 
            onsuccess={handleSuccess} onsubmit ={handleSubmit}>
        <lightning-messages>
        </lightning-messages>
        <lightning-output-field field-name="AccountId">
        </lightning-output-field>
        <lightning-input-field field-name="FirstName">
        </lightning-input-field>
        <lightning-input-field field-name="LastName">
        </lightning-input-field>
        <lightning-input-field field-name="Email">
        </lightning-input-field>
        <lightning-button class="slds-m-top_small" variant="brand" type="submit" name="update" label="Update">
        </lightning-button>
    </lightning-record-edit-form>
</template>

Please note that onsuccess and onsubmit are optional here and are used for Overriding Default Behaviors. Here I added these for testing.

recordEditFormEditExampleLWC.js

import { LightningElement, api} from 'lwc';
export default class RecordEditFormEditExampleLWC extends LightningElement {
    @api recordId;
    handleSubmit(event) {
        console.log('onsubmit event recordEditForm'+ event.detail.fields);
    }
    handleSuccess(event) {
        console.log('onsuccess event recordEditForm', event.detail.id);
    }
}

recordEditFormEditExampleLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this LWC component on the Contact Record page.

  • Go to Contact record
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your recordEditFormEditExampleLWC component and drag it on Contact Page.
  • Click Save and activate.

 

We will get the following output

lightning-record-edit-form LWC Edit Record

 

Creating a Record

To enable record creation, pass in the object API name for the record to be created. Specify the fields you want to include in the record create layout using lightning-input-field components. For more information, see the lightning-input-field documentation.

Include a lightning-button component with type=”submit” to automatically save the record when the button is clicked.

Let’s create an example to create account record using lightning-record-edit-form in Lightning Web Component

recordEditFormCreateExampleLWC.html

<template>
    <lightning-record-edit-form object-api-name="Contact" onsuccess={handleSuccess} onsubmit ={handleSubmit}>
        <lightning-messages>
        </lightning-messages>
        <lightning-input-field field-name='AccountId'></lightning-input-field>
        <lightning-input-field field-name='FirstName'></lightning-input-field>
        <lightning-input-field field-name='LastName'></lightning-input-field>
        <lightning-input-field field-name='Email'></lightning-input-field>
        <lightning-button class="slds-m-top_small" type="submit" label="Create Contact">
        </lightning-button>
    </lightning-record-edit-form>
</template>

recordEditFormCreateExampleLWC.js

import { LightningElement} from 'lwc';
export default class RecordEditFormCreateExampleLWC extends LightningElement {
    handleSuccess(event) {
        console.log('onsuccess event recordEditForm',event.detail.id)
    }
    handleSubmit(event) {
        console.log('onsubmit event recordEditForm'+ event.detail.fields);
    }
}

recordEditFormCreateExampleLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this LWC component on the Contact Record page.

  • Go to Contact record.
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your recordEditFormCreateExampleLWC component and drag it on Contact Page.
  • Click Save and activate.

 

We will get the following output

lightning-record-edit-form LWC Create Record

 

Displaying Forms Based on a Record Type

If your org uses record types, picklist fields display values according to your record types. You must provide a record type ID using the record-type-id attribute if you have multiple record types on an object and you don’t have a default record type. Otherwise, the default record type ID is used.

Supported Objects

This component doesn’t support all Salesforce standard objects. For example, the Event and Task objects are not supported. This limitation also applies to a record that references a field that belongs to an unsupported object.

External objects and person accounts are not supported.

To work with the User object, specify FirstName and LastName instead of the Name compound field for the field-name values of lightning-input-field.

Error Handling

lightning-record-edit-form handles field-level validation errors and Lightning Data Service errors automatically. For example, entering an invalid email format for the Email field results in an error message when you move focus away from the field. Similarly, a required field like the Last Name field displays an error message when you leave the field blank and move focus away.

We need to include lightning-messages to support error handling and displaying of error messages. If the record edit layout includes a lightning-button component with type="submit", when the button is clicked the lightning-record-edit-form component automatically performs error handling and saves any changes in the input fields. Similarly, if the record create layout provides a submit button, when the button is clicked error handling is automatically performed and a new record is created with the input data you provide.

 

For more details please refer to official link

Permanent link to this article: https://www.sfdcpoint.com/salesforce/lightning-record-edit-form-lwc/

Lightning Spinner in LWC (Lightning Web Component)

Lightning Spinner in LWC (Lightning Web Component)

What is Lightning Spinner in LWC?

Lightning Spinners are CSS loading indicators that should be shown when retrieving data or performing slow computations. lightning-spinner displays an animated spinner image to indicate that a request is loading. This component can be used when retrieving data or performing an operation that takes time to complete. In some cases, the first time a parent component loads, a stencil is preferred to indicate network activity.

lightning-spinner LWC example

Let’s first see a very simple example to show or hide lightning spinner using a toggle button

lightningSpinnerLWCSimpleExample.html

<template>
    <lightning-button label="Toggle" variant="brand" onclick={handleClick}>
    </lightning-button>
    <div class="slds-m-around_large">
        <p if:true={isLoaded}>Content has been loaded.</p>
         <div if:false={isLoaded} class="slds-is-relative">
            <lightning-spinner
                alternative-text="Loading..." variant="brand">
            </lightning-spinner>
        </div>
    </div>
</template>

lightningSpinnerLWCSimpleExample.js

import { LightningElement, api } from 'lwc';
export default class LightningSpinnerLWCSimpleExample extends LightningElement {
    @api isLoaded = false;
    // change isLoaded to the opposite of its current value
    handleClick() {
        this.isLoaded = !this.isLoaded;
    }
}

lightningSpinnerLWCSimpleExample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this LWC component on the home page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your lightningSpinnerLWCSimpleExample component and drag it on right-hand side top.
  • Click Save and activate.

 

We will see the following output.  If the user will click on the toggle button then the spinner will toggle on or off.

Lightning Spinner in LWC Toggle Example

 

 

lightning-spinner example with Apex

Let’s see one more  real-life example where the user will click on the button to load account and during apex request lightning spinner loading image

AccountHelper class

public with sharing class AccountHelper {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Type, Rating,
                Phone, Website, AnnualRevenue
            FROM Account];
    }
}

lightningSpinnerLWCExample.html

<template>
    <div class="spinner">
        <template if:true={isLoading}>
             <lightning-spinner alternative-text="Loading" variant="brand" size="large">
             </lightning-spinner>
        </template>
    </div>
    <lightning-card title="Account List lightning-spinner LWC" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <p class="slds-m-bottom_small">
                <lightning-button label="Load Accounts" onclick={handleLoad}></lightning-button>
            </p>
            <template if:true={accounts}>
                <template for:each={accounts} for:item="acc">
                    <p key={acc.Id}>{acc.Name}</p>
                </template>
            </template>
            <template if:true={error}>
                {error}
            </template>
        </div>
    </lightning-card>
</template>

lightningSpinnerLWCExample.js

import { LightningElement, track } from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
export default class LightningSpinnerLWCExample extends LightningElement {
    @track accounts;
    @track error;
    @track isLoading = false;
    handleLoad() {
        this.isLoading = true;
        getAccountList()
            .then(result =&gt; {
                this.accounts = result;
                this.isLoading = false;
            })
            .catch(error =&gt; {
                this.error = error;
                this.isLoading = false;
            });
    }
}

lightningSpinnerLWCExample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this LWC component on the home page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your lightningSpinnerLWCExample component and drag it on right-hand side top.
  • Click Save and activate.

We will see the following output when the user will click on the Load Accounts button. When loading will finish, the user will see the account list.

 

Lightning Spinner in LWC

 

Users will see the following account list when loading completes.

 

Lightning Spinner in LWC Loading finish

 

 

For more details please refer to official link

Permanent link to this article: https://www.sfdcpoint.com/salesforce/lightning-spinner-in-lwc-lightning-web-component/

Lightning Web Component(LWC) Toast Messages

Lightning Web Component(LWC) Toast Messages

LWC Toast Messages

Lightning Web component(LWC) can send a toast notification that pops up to alert users of success, error or warning. A toast can also simply provide information. To display a toast notification in Lightning Experience or Lightning communities, import ShowToastEvent from the lightning/platformShowToastEvent module. We can dispatch this toast on some event like click of button.

 

How to add toast message in Lightning Web component(LWC)

Import Toast Message

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

Dispatch toast Message

showToast() {
    const event = new ShowToastEvent({
        title: 'Toast message',
        message: 'Toast Message',
        variant: 'success',
        mode: 'dismissable'
    });
    this.dispatchEvent(event);
}

 

Here are some point about toast message:

  • We can style toast to provide error, success, warning and information message using mode parameter.
  • We can also configure the visibility of the toast using variant. It can remain visible for three seconds, until the user clicks to dismiss it, or a combination of both.
  • To trigger a toast from a Lightning web component, in the component’s JavaScript class, import ShowToastEventfrom lightning/platformShowToastEvent.
  • Create a ShowToastEvent with a few parameters, and dispatch it.

Types of toast messages Lightning Web Component(LWC)

Error Toast

showErrorToast() {
    const evt = new ShowToastEvent({
        title: 'Toast Error',
        message: 'Some unexpected error',
        variant: 'error',
        mode: 'dismissable'
    });
    this.dispatchEvent(evt);
}

Success Toast

showSuccessToast() {
    const evt = new ShowToastEvent({
        title: 'Toast Success',
        message: 'Opearion sucessful',
        variant: 'success',
        mode: 'dismissable'
    });
    this.dispatchEvent(evt);
}

Warning Toast

showWarningToast() {
    const evt = new ShowToastEvent({
        title: 'Toast Warning',
        message: 'Some problem',
        variant: 'warning',
        mode: 'dismissable'
    });
    this.dispatchEvent(evt);
}

Info Toast

showInfoToast() {
    const evt = new ShowToastEvent({
        title: 'Toast Info',
        message: 'Operation will run in background',
        variant: 'info',
        mode: 'dismissable'
    });
    this.dispatchEvent(evt);
}

LWC Toast Messages Example

toastNotificationExampleLWC.html

<template>
    <lightning-card title="Notification" icon-name="custom:custom19">
        <lightning-button label="Show Error" onclick={showErrorToast}></lightning-button>
        <lightning-button label="Show Success" onclick={showSuccessToast}></lightning-button>
        <lightning-button label="Show Warning" onclick={showWarningToast}></lightning-button>
        <lightning-button label="Show Info" onclick={showInfoToast}></lightning-button>
    </lightning-card>
</template>

toastNotificationExampleLWC.js

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class ToastNotificationExampleLWC extends LightningElement {
    showErrorToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Error',
            message: 'Some unexpected error',
            variant: 'error',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    showSuccessToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Success',
            message: 'Opearion sucessful',
            variant: 'success',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    showWarningToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Warning',
            message: 'Some problem',
            variant: 'warning',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
    showInfoToast() {
        const evt = new ShowToastEvent({
            title: 'Toast Info',
            message: 'Operation will run in background',
            variant: 'info',
            mode: 'dismissable'
        });
        this.dispatchEvent(evt);
    }
}

toastNotificationExampleLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this LWC component on the home page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your toastNotificationExampleLWC component and drag it on right-hand side top.
  • Click Save and activate.

 

We will get the following output

Lightning Web component(LWC) Toast Messages

 

Here is list of Toast Event Parameters:

PARAMETERTYPEDESCRIPTION
titleStringThe title of the toast, displayed as a heading.
messageStringA string containing a message for the user.
messageDataString[] or Objecturl and label values that replace the {index} placeholders in the message string.
variantStringThe theme and icon displayed in the toast. Valid values are:

info—(Default) A gray box with an info icon.
success—A green box with a checkmark icon.
warning—A yellow box with a warning icon.
error—A red box with an error icon.
modeStringDetermines how persistent the toast is. Valid values are:

dismissable—(Default) Remains visible until the user clicks the close button or 3 seconds has elapsed, whichever comes first.
pester—Remains visible for 3 seconds.
sticky—Remains visible until the user clicks the close button.

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/lightning-web-component-lwc-toast-messages/

Custom Labels In Lightning Aura Component

Custom Labels In Lightning Aura Component

Custom Labels In Lightning Aura Component

Custom labels are custom text values that can be accessed from  Aura Component, LWC Component, Apex classes, Visualforce pages. The values can be translated into any language Salesforce supports. Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language.

To access custom labels in Aura components, use the $Label global value provider. In this post we will see how to use custom label in lightning aura component. If you want to add custom label in lwc please refer Custom Labels In Lightning Web Component(LWC)

Create Custom Labels

Go To Setup — Create — Custom Labels. Click on New Custom Labels. Enter value for name, value and description. We can use custom label name to access custom label value in apex code using System.Label.labelName

The advantage of using a custom label is that label will be displayed to user depending on their language automatically. We need to specify translation for label using translation workbench.

Use Custom Labels in Lightning Aura Component

Use the following syntax to access custom labels in Aura components.

  • $Label.c.labelName for the default namespace
  • $Label.namespace.labelName if your org has a namespace, or to access a label in a managed package

 

Use Custom Labels in Lightning Aura Component javascript controller

Use the following syntax to access custom labels in Aura components.

  • $A.get(“$Label.c.labelName”) for the default namespace
  • $A.get(“$Label.namespace.labelName”) if your org has a namespace, or to access a label in a managed package

 

Custom Label in Lightning Aura Component Example

First, let’s create 3 labels from Setup — Create — Custom Labels. Click on New Custom Labels. Enter value for name, value and description.

  • WelcomeNoteLabel: Welcome to SFDCPOINT
  • HomePageNewsLabel: Your home page news
  • NewCaseLabel: New Case

 

We will add two custom labels value in aura component and 3rd custom label value will be added in aura component by setting value to attribute using javascript controller on click of button.

Now create new lightning web component with name customLabelExampleLWC. Here is code

customLabelExampleAura.cmp

<aura:component implements="flexipage:availableForAllPageTypes">
    <aura:attribute name="homePageNews" type="String" />
    <lightning:card title="{!$Label.c.WelcomeNoteLabel}">
        <p>
            <lightning:button variant="brand" label="{!$Label.c.NewCaseLabel}" onclick="{!c.newCaseAction}"/>
        </p>
        <p>{!v.homePageNews}</p>
    </lightning:card>
</aura:component>

customLabelExampleAuraController.js

({
    newCaseAction : function(component, event, helper) {
        var homePageNewslabel = $A.get("$Label.c.HomePageNewsLabel");
        component.set('v.homePageNews', homePageNewslabel);
    }
})

Now we can add this lightning aura component on the home page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your customLabelExampleAura component and drag it on right-hand side top.
  • Click Save and activate.

 

User will see custom label values in aura component. When user will click on the New Case button then one more custom label value will be retrieved from aura component controller using attribute. We will get the following output

Custom Labels In Lightning Aura Component

 

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/custom-label-in-lightning-aura-component/

Custom Labels In Lightning Web Component(LWC)

Custom Labels In Lightning Web Component(LWC)

Custom Labels In Lightning Web Component(LWC)

Custom labels are custom text values that can be accessed from LWC Component, Aura Component, Apex classes, Visualforce pages. The values can be translated into any language Salesforce supports. Custom labels enable developers to create multilingual applications by automatically presenting information (for example, help text or error messages) in a user’s native language.

In this post we will see how to use custom label in LWC component. If you want to add custom label in aura component please refer Custom Labels In Lightning Aura Component

Create Custom Labels

Go To Setup — Create — Custom Labels. Click on New Custom Labels. Enter value for name, value and description. We can use custom label name to access custom label value in apex code using System.Label.labelName

The advantage of using a custom label is that label will be displayed to user depending on their language automatically. We need to specify translation for label using translation workbench.

Use Custom Labels in LWC

Using custom label in LWC is easy. To import a label in a Lightning Web Component JavaScript file, use @salesforce/label in an import statement.

import labelName from '@salesforce/label/label-reference';
  • labelName: It is name that refers to the label in LWC.
  • labelReference: The name of the label in your org in the format namespace.labelName. If there is no namespace then simply use labelName.

Custom Labels In Lightning Web Component(LWC) Example

First, let’s create 3 labels from Setup — Create — Custom Labels. Click on New Custom Labels. Enter value for name, value and description.

  • WelcomeNoteLabel: Welcome to SFDCPOINT
  • HomePageNewsLabel: Your home page news
  • NewCaseLabel: New Case

Now create new lightning web component with name customLabelExampleLWC. Here is code

customLabelExampleLWC.html

<template>
    <lightning-card  title={label.WelcomeLabel} variant="narrow">
        <p>
            <lightning-button label={label.NewCaseLabel}></lightning-button>
        </p>
        <p>{label.HomePageLabel}</p>
    </lightning-card>
</template>

customLabelExampleLWC.js

import { LightningElement } from 'lwc';
// importing Custom Label
import WelcomeLabel from '@salesforce/label/c.WelcomeNoteLabel';
import HomePageLabel from '@salesforce/label/c.HomePageNewsLabel';
import NewCaseLabel from '@salesforce/label/c.NewCaseLabel';
export default class CustomLabelExampleLWC extends LightningElement {
    label = {
        WelcomeLabel,
        HomePageLabel,
        NewCaseLabel
    };
}

customLabelExampleLWC.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this lwc component on home page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your modalPopupLWC component and drag it on right-hand side top.
  • Click Save and activate.

 

We will get the following output

Custom Labels In Lightning Web Component(LWC)

For more details please refer to official link

Permanent link to this article: https://www.sfdcpoint.com/salesforce/custom-labels-in-lightning-web-component-lwc/