Salesforce Summer ’20 Release Notes

Salesforce Summer ’20 Release Notes

All you need to know about Salesforce Summer ’20 Release Notes

Salesforce Summer ’20 Release Notes: I hope everyone is safe and taking all the care to cross the hurdle of Covid-19. I am sure you have started enjoying the quarantine time with family and friends trying to have fun as well as learning new stuff. To enhance your learning mode, Here comes the summary of some cool and important features for admins and developers in Salesforce Summer ’20 Release.

Salesforce Summer 20 Release Notes

Split List View

Work Through Lists with Ease Using Split View for Standard Navigation.

Do you often find yourself working through multiple records in a list? With split view, you can see a list view and a record side by side. To move on to a new record, select it from the split view, and the new record opens with the list still in view. No more navigating back and forth between your list and your records. Split view is great for going through records in sequence or for quickly skimming through a set of records. The split view panel is collapsible for extra flexibility.

How: To access split view, select Split View from the Display As dropdown menu. If you select split view for an object, that object automatically loads in split view until you change its Display As view.

Salesforce Summer 20 split view table

split view opened record

Dynamic Forms

Break Up Your Record Details with Dynamic Forms (Non-GA Preview)

Dynamic Forms is the next step in the evolution of Lightning record pages. It adds the ability to configure record detail fields and sections inside the Lightning App Builder.

With Dynamic Forms, you can migrate the fields and sections from your page layout as individual components into the Lightning App Builder. Then, you can configure them just like the rest of the components on the page, and give users only the fields and sections that they need.

dynamic form add fields

In-App Guidance Builder

It’s easier and more intuitive to create prompts and walkthroughs. To make way for walkthroughs, the user interface for authoring in-app guidance is now similar to other builder tools in Salesforce.

From Setup in Lightning Experience, enter In-App Guidance in the Quick Find box, and then select In-App Guidance. Click Add to open the In-App Guidance Builder in a new tab.

In-App Guidance Builder Salesforce Summer 20

View Records Using Full View (Generally Available)

Now you have two record page view default options. Choose between the current view—now called Grouped view—and the new Full view. Full view displays all details and related lists on the same page(Similar to classic). If you’re transitioning to Lightning Experience, this view is similar to Salesforce Classic. This feature, which is generally available, includes the same functionality as the beta release and is available to qualifying Salesforce orgs.

View Records Using Full View Salesforce Summer 20

Set Up Alerts for Big Deals in Lightning Experience

You can now use Lightning Experience to set up automatic email notifications for opportunities that reach a threshold of amount and probability. Previously, setting up Big Deal Alerts required you to switch to Salesforce Classic.

Where: This change applies to Lightning Experience in Group, Professional, Enterprise, Performance, Unlimited, and Developer Editions.

How: In Setup, use the Quick Find box to find Big Deal Alerts. In the Sender Email field, enter your own Salesforce email address or a verified org-wide email. You must have the View All Data permission to set up alerts.

Einstein Search

Einstein Search: Clearer Setup Process, Natural Language Search Examples, and Better Recommended Results on the Salesforce Mobile App (Beta).

You can turn on Einstein Search at no additional cost and benefit from all it has to offer. Complete all the steps outlined by a clearer setup process. Learn how to use natural language search by following examples. See improved recommended results on the mobile app.

Einstein Search is personal, natural, and actionable. To give your users the full Einstein Search experience, enable all Einstein Search features. Begin in Setup, where the option is now labeled Enable Einstein Search. This page lists the steps to turn on personalization, natural language search, and enhanced instant results.

Natural language search lets users enter common words and phrases in the search box to find the records that they want. Natural language search is supported for accounts, cases, contacts, leads, and opportunities.

Einstein Vision: Detect Text in Images with Einstein OCR

Get optical character recognition (OCR) models that detect alphanumeric text in an image with Einstein OCR. You access the models from a single REST API endpoint.

New and Changed Lightning Web Components

The following components have changed.

  • lightning-badge
  • lightning-breadcrumb
  • lightning-datatable
  • lightning-input
  • lightning-input-field
  • lightning-tabset
  • lightning-tree-grid

Please refer to the Component Library for more details

For all the features for Summer 20 Release Notes, please refer to the Salesforce website.

Salesforce Summer 20 Release Date

Here’s the new Summer ’20 release schedule:

  • Sandbox preview: May 29-30, 2020
  • Summer ’20 Production release
    • First Release window: June 12
    • Second Release window: July 10
    • Third Release window: July 17-18, 2020

 

On March 16, 2020, our CEO Marc Benioff shared an update regarding our response to COVID-19 and reiterated our commitment to continue to deliver the highest levels of performance, availability, and security. That commitment includes making any necessary adjustments to create stability and consistency for our customers.

Salesforce Summer ’20 Release Date Schedule Calendar

The Sandbox Preview window for Summer ‘20 begins on May 29, 2020. Get early access and take advantage of exciting new features, functionality, and customizations

Summer 20 release calendar

For more details on the release calendar, please visit salesforce website.

Stay Home, Stay Safe, and Stay Healthy. Let’s fight the pandemic together.

Covid 19 Stay safe

Happy Learning 🙂

Permanent link to this article: https://www.sfdcpoint.com/salesforce/salesforce-summer-20-release-notes/

Wrapper Class in LWC(Lightning Web Component)

Wrapper Class in LWC(Lightning Web Component)

Wrapper Class in LWC Lightning Web Component

A wrapper or container class is a class, a data structure, or an abstract data type which contains different objects or collection of objects as its members. In this post we will see how we can use wrapper class in lightning component to display data in lightning component. For details about how we can use wrapper class in visualforce page  check wrapper class in Apex. If you are looking for wrapper class in Lightning Aura component, please refer to wrapper class in lightning component salesforce.

Wrapper Class in LWC Example

Let’s see an example of wrapper class in LWClightning component salesforce. In this example, we will create AcoountContactWrapper and will display account and contact details and display on lightning web component.

Apex class controller with the wrapper class

AccountContactController.cls

public class AccountContactController{
     
    @AuraEnabled(cacheable=true)
    public static List<AccountContactListWrapper> getAllAccountWithContacts(){
        List<AccountContactListWrapper> accWrapperList = new List<AccountContactListWrapper>();
        List<Account> accList = [SELECT Id, Name, BillingState, Website, Phone,
                                    (SELECT Id, FirstName, LastName, Name, Email From Contacts)
                                    FROM Account WHERE Name LIMIT 5];
        if(!accList.isEmpty()){
            for(Account acc : accList){
                AccountContactListWrapper accWrapper = new AccountContactListWrapper();
                accWrapper.accRecord = acc;
                accWrapper.contactList = acc.Contacts;
                accWrapper.contactCount = acc.Contacts.size();
                accWrapperList.add(accWrapper);
            }
        }
        return accWrapperList;
    }
     
    // wrapper class with @AuraEnabled and {get;set;} properties 
    public class AccountContactListWrapper{
        @AuraEnabled
        public Account accRecord{get;set;}
        @AuraEnabled
        public List<Contact> contactList{get;set;}
        @AuraEnabled
        public Integer contactCount{get;set;}
    }
}

wrapperClassExampleLWC.html

<template>
    <lightning-card title="Account with Contacts using wrapper class in LWC" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <template if:true={accountsWithContacts}>
                <template for:each={accountsWithContacts} for:item="accWithContacts">
                    <div key={accWithContacts.accRecord.Id}>
                        <div class="slds-text-heading_medium">{accWithContacts.accRecord.Name}</div>
                        <template if:true={accWithContacts.contactList}>
                            Contacts Count is {accWithContacts.contactCount}. Here is list:
                            <ul class="slds-list_dotted">
                                <template for:each={accWithContacts.contactList} for:item="con">
                                    <li key={con.Id}>{con.Name}</li>
                                </template>
                            </ul>
                        </template>
                    </div>
                </template>
            </template>
            <template if:true={error}>
                {error}
            </template>
        </div>
    </lightning-card>
</template>

wrapperClassExampleLWC.js

import { LightningElement, wire, track } from 'lwc';
import getAllAccountWithContactsList from '@salesforce/apex/AccountContactController.getAllAccountWithContacts';
export default class WrapperClassExampleLWC extends LightningElement {
    @track accountsWithContacts;
    @track error;
    @wire(getAllAccountWithContactsList)
    wiredAccountsWithContacts({ error, data }) {
        if (data) {
            this.accountsWithContacts = data;
        } else if (error) {
            console.log(error);
            this.error = error;
        }
    }
}

wrapperClassExampleLWC.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 wrapperClassExampleLWC component and drag it on right hand side top.
  • Click Save and activate.

 

We will have the following output:

Wrapper Class in LWC

 

For more details about LWC, refer to official link.

Happy Coding 🙂

Permanent link to this article: https://www.sfdcpoint.com/salesforce/wrapper-class-in-lwc/

Navigation Service in LWC(Lightning Web Components)

Navigation Service in LWC(Lightning Web Components)

Navigation Service in LWC(Lightning Web Components)

To navigate in Lightning Experience, Lightning Communities, and the Salesforce app, use the navigation service, lightning/navigation.

The lightning/navigation service is supported only in Lightning Experience, Lightning Communities, and the Salesforce app. It isn’t supported in other containers, such as Lightning Components for Visualforce, or Lightning Out. This is true even if you access these containers inside Lightning Experience or the Salesforce app. We can use navigation services in LWC to Navigate to Pages, Records, and Lists.

There are different types of navigation options available. Let’s discuss the basic one

Basic Navigation

Use the navigation service, lightning/navigation, to navigate to many different page types, like records, list views, and objects. Also use the navigation service to open files.

Instead of a URL, the navigation service uses a PageReference. A PageReference is a JavaScript object that describes the page type, its attributes, and the state of the page. Using a PageReference insulates your component from future changes to URL formats. It also allows your component to be used in multiple applications, each of which can use different URL formats.

Navigation service uses a PageReference. PageReference is a JavaScript object that describes the page type, its attributes, and the state of the page.

Page type(String) and attributes(Object) are required parameters, state(Object) is optional parameter.

Use Navigation Service in LWC

Here are steps to use the navigation service

  1. First, we need to import the lightning/navigation module.
    import { NavigationMixin } from 'lightning/navigation';
    
  2. Apply the NavigationMixin function to your component’s base class.
    export default class MyCustomElement extends NavigationMixin(LightningElement) {}
    
  3. Create a plain JavaScript PageReference object that defines the page
  4. To dispatch the navigation request, call the navigation service’s [NavigationMixin.Navigate](pageReference, [replace])
    navigateNext() {
           this[NavigationMixin.Navigate]({
               type: 'standard__navItemPage',
               attributes: {
                   apiName: this.tabName,
               },
           });
       }
    

The NavigationMixin adds two APIs to your component’s class. Since these APIs are methods on the class, they must be invoked with this reference.

  • [NavigationMixin.Navigate](pageReference, [replace]): A component calls this[NavigationMixin.Navigate] to navigate to another page in the application.
  • [NavigationMixin.GenerateUrl](pageReference): A component calls this[NavigationMixin.GenerateUrl] to get a promise that resolves to the resulting URL. The component can use the URL in the href attribute of an anchor. It can also use the URL to open a new window using the window.open(url) browser API.

 

Navigation Service in LWC Example

navigationExampleLWC.html

<template>
    <lightning-card title="Navigation Service in LWC(Lightning Web Components)">
        <lightning-card title="Navigate To Record Example">
            <lightning-button label="New Account" onclick={navigateToNewAccountPage}></lightning-button>
            <lightning-button label="View Account" onclick={navigateToViewAccountPage}></lightning-button>
            <lightning-button label="Edit Account" onclick={navigateToEditAccountPage}></lightning-button>
        </lightning-card>
        <lightning-card title="Navigate To Views">
            <lightning-button label="Account Recent list View" onclick={navigateToAccountListView}></lightning-button>
            <lightning-button label="Account Related List" onclick={navigateToContactRelatedList}></lightning-button>
        </lightning-card>
        <lightning-card title="Navigate To Home">
            <lightning-button label="Navigate to Home" onclick={navigateToHomePage}></lightning-button>
            <lightning-button label="Navigate to Contact Home " class="slds-m-around_medium" onclick={navigateToContactHome}></lightning-button>
        </lightning-card>
        <lightning-card title="Navigate To Other">
            <lightning-button label="Navigate to Chatter Home" onclick={navigateToChatter}></lightning-button>
            <lightning-button label="Navigate to Reports" onclick={navigateToReports}></lightning-button>
            <lightning-button label="Navigate to Tab" onclick={navigateToTab}></lightning-button>
            <lightning-button label="Navigate to SFDCPoint" onclick={navigateToWebPage}></lightning-button>
            <lightning-button label="Navigate to Files " class="slds-m-around_medium" onclick={navigateToFilesHome}></lightning-button>
        </lightning-card>
        <lightning-card title="Navigate To Component">
            <lightning-button label="Navigate to Visualforce page " onclick={navigateToVFPage}></lightning-button>
            <lightning-button label="Navigate to Aura Lightning Component " class="slds-m-around_medium" onclick={navigateToLightningComponent}></lightning-button>
        </lightning-card>
    </lightning-card>
</template>

navigationExampleLWC.js

import { LightningElement, api } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';
export default class NavigationExampleLWC extends NavigationMixin(LightningElement) {
    @api recordId;
    // Navigate to New Account Page
    navigateToNewAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'new'
            },
        });
    }
    // Navigate to View Account Page
    navigateToViewAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                actionName: 'view'
            },
        });
    }
    // Navigate to Edit Account Page
    navigateToEditAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                actionName: 'edit'
            },
        });
    }
    // Navigation to Account List view(recent)
    navigateToAccountListView() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'list'
            },
            state: {
                filterName: 'Recent'
            },
        });
    }
    // Navigation to Contact related list of account
    navigateToContactRelatedList() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordRelationshipPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                relationshipApiName: 'Contacts',
                actionName: 'view'
            },
        });
    }
    //Navigate to home page
    navigateToHomePage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'home'
            },
        });
    }
    // Navigation to contant object home page
    navigateToContactHome() {
        this[NavigationMixin.Navigate]({
            "type": "standard__objectPage",
            "attributes": {
                "objectApiName": "Contact",
                "actionName": "home"
            }
        });
    }
    //Navigate to chatter
    navigateToChatter() {
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'chatter'
            },
        });
    }
    //Navigate to Reports
    navigateToReports() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Report',
                actionName: 'home'
            },
        });
    }
    //Navigate to Files home
    navigateToFilesHome() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'ContentDocument',
                actionName: 'home'
            },
        });
    }
    // Navigation to lightning component
    navigateToLightningComponent() {
        this[NavigationMixin.Navigate]({
            "type": "standard__component",
            "attributes": {
                //Here customLabelExampleAura is name of lightning aura component
                //This aura component should implement lightning:isUrlAddressable
                "componentName": "c__customLabelExampleAura"
            }
        });
    }
    // Navigation to web page 
    navigateToWebPage() {
        this[NavigationMixin.Navigate]({
            "type": "standard__webPage",
            "attributes": {
                "url": "https://www.sfdcpoint.com/"
            }
        });
    }
    //Navigate to visualforce page
    navigateToVFPage() {
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__webPage',
            attributes: {
                url: '/apex/AccountVFExample?id=' + this.recordId
            }
        }).then(generatedUrl => {
            window.open(generatedUrl);
        });
    }
    // Navigation to Custom Tab
    navigateToTab() {
        this[NavigationMixin.Navigate]({
            type: 'standard__navItemPage',
            attributes: {
                //Name of any CustomTab. Visualforce tabs, web tabs, Lightning Pages, and Lightning Component tabs
                apiName: 'CustomTabName'
            },
        });
    }
}

navigationExampleLWC.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 Account detail record page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your navigationExampleLWC component and drag it on right-hand side top.
  • Click Save and activate.

 

We will get the following output

Navigation Service in LWC

Navigate to New Record LWC

// Navigate to New Account Page
    navigateToNewAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'new'
            },
        });
    }

Navigate to View Record LWC

// Navigate to View Account Page
    navigateToViewAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                actionName: 'view'
            },
        });
    }

Navigate to the Edit Record LWC

// Navigate to Edit Account Page
    navigateToEditAccountPage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                actionName: 'edit'
            },
        });
    }

Navigate to List View LWC

// Navigation to Account List view(recent)
    navigateToAccountListView() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'list'
            },
            state: {
                filterName: 'Recent'
            },
        });
    }

Navigate to Related List LWC

// Navigation to Contact related list of account
    navigateToContactRelatedList() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordRelationshipPage',
            attributes: {
                recordId: this.recordId,
                objectApiName: 'Account',
                relationshipApiName: 'Contacts',
                actionName: 'view'
            },
        });
    }

Navigate to Home Page LWC

//Navigate to home page
    navigateToHomePage() {
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'home'
            },
        });
    }

Navigate to Object Home LWC

// Navigation to contant object home page
    navigateToContactHome() {
        this[NavigationMixin.Navigate]({
            "type": "standard__objectPage",
            "attributes": {
                "objectApiName": "Contact",
                "actionName": "home"
            }
        });
    }

Navigate to Chatter Home LWC

//Navigate to chatter
    navigateToChatter() {
        this[NavigationMixin.Navigate]({
            type: 'standard__namedPage',
            attributes: {
                pageName: 'chatter'
            },
        });
    }

Navigate to Reports Tab LWC

//Navigate to Reports
    navigateToReports() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Report',
                actionName: 'home'
            },
        });

Navigate to Files Home LWC

//Navigate to Files home
    navigateToFilesHome() {
        this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'ContentDocument',
                actionName: 'home'
            },
        });
    }

Navigate to Lightning Component LWC

// Navigation to lightning component
    navigateToLightningComponent() {
        this[NavigationMixin.Navigate]({
            "type": "standard__component",
            "attributes": {
                //Here customLabelExampleAura is name of lightning aura component
                //This aura component should implement lightning:isUrlAddressable
                "componentName": "c__customLabelExampleAura"
            }
        });
    }

Navigate to Web Page LWC

// Navigation to web page 
    navigateToWebPage() {
        this[NavigationMixin.Navigate]({
            "type": "standard__webPage",
            "attributes": {
                "url": "https://www.sfdcpoint.com/"
            }
        });
    }

Navigate to Visualforce page LWC

//Navigate to visualforce page
    navigateToVFPage() {
        this[NavigationMixin.GenerateUrl]({
            type: 'standard__webPage',
            attributes: {
                url: '/apex/AccountVFExample?id=' + this.recordId
            }
        }).then(generatedUrl => {
            window.open(generatedUrl);
        });
    }

Navigate to Custom Tab LWC

// Navigation to Custom Tab
    navigateToTab() {
        this[NavigationMixin.Navigate]({
            type: 'standard__navItemPage',
            attributes: {
                //Name of any CustomTab. Visualforce tabs, web tabs, Lightning Pages, and Lightning Component tabs
                apiName: 'CustomTabName'
            },
        });
    }

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/navigation-service-in-lwc/

for:each template directives in LWC

for:each template directives in LWC

for:each template directives in LWC(Lightning Web Component)

To render a list of items, use for:each directive or the iterator directive to iterate over an array. Add the directive to a nested <template> tag that encloses the HTML elements you want to repeat. We can call it for loop in LWC.

The iterator directive has first and last properties that let you apply special behaviors to the first and last items in an array.

Regardless of which directive you use, you must use a key directive to assign a unique ID to each item. When a list changes, the framework uses the key to rerender only the item that changed. The key in the template is used for performance optimization and isn’t reflected in the DOM at run time.

for:each LWC(Lightning Web Component)

When using the for:each directive, use for:item=”currentItem” to access the current item. This example doesn’t use it, but to access the current item’s index, use for:index=”index”.

To assign a key to the first element in the nested template, use the key={uniqueId} directive.

for:each LWC example

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;
}

Here we are calling apex method to get account list. For more details refer to Call Apex Methods In LWC(Lightning web components)

accountListForEachLWC.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 accountListForEachLWC component and drag it on right hand side top.
  • Click Save and activate.

We will have the following output:

for each template directives in LWC

 

 

iterator in LWC(Lightning Web Component)

To apply special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use the iterator directive on a template tag.

Use iteratorName to access these properties:

  • value—The value of the item in the list. Use this property to access the properties of the array. For example, iteratorName.value.propertyName.
  • index—The index of the item in the list.
  • first—A boolean value indicating whether this item is the first item in the list.
  • last—A boolean value indicating whether this item is the last item in the list.

 

iterator LWC Example

accountListIteratorLWC.html

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

accountListIteratorLWC.js

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

accountListIteratorLWC.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>

Steps to add this component to the Home page is the same and output will also be the same.

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/foreach-template-directives-in-lwc/

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/