Decorators in Lightning Web Component(LWC)

Decorators in Lightning Web Component(LWC)

Decorators in Lightning Web Component(LWC)

The Lightning Web Components programming model has three decorators that add functionality to property or function. Decorators dynamically alter the functionality of a property or function. The ability to create decorators is part of ECMAScript, but these three decorators are unique to Lightning Web Components.

  • @api: To expose a public property, decorate it with @api. Public properties define the API for a component. An owner component that uses the component in its markup can access the component’s public properties. Public properties are reactive. If the value of reactive property changes, the component’s template rerenders any content that references the property.
  • @track: To track a private property’s value and rerender a component when it changes, decorate the property with @track. Tracked properties are also called private reactive properties.
  • @wire: To read Salesforce data, Lightning web components use a reactive wire service. When the wire service provisions data, the component rerenders. Components use @wire in their JavaScript class to specify a wire adaptor or an Apex method.

 

Here are three decorators in LWC in more details

@api

Public properties are reactive. If the value of public property changes, the component rerenders. To expose a public property, decorate a field with @api. Public properties define the API for a component.

To expose a public method, decorate it with @api. Public methods are part of a component’s API. To communicate down the containment hierarchy, owner and parent components can call JavaScript methods on child components.

Import @api decorator from lwc

import { LightningElement, api } from 'lwc';

@api Example

todoItem.js

// todoItem.js
import { LightningElement, api } from 'lwc';
export default class TodoItem extends LightningElement {
    @api itemName = 'New Item';
}

todoItem.html

<!-- todoItem.html -->
<template>
    <div class="view">
        <label>{itemName}</label>
    </div>

todoApp.html

<!-- todoApp.html -->
<template>
    <div class="listing">
        <c-todo-item item-name="Milk"></c-todo-item>
        <c-todo-item item-name="Bread"></c-todo-item>
    </div>
</template>

 

@track

Fields are reactive. If a field’s value changes, and the field is used in a template or in a getter of a property that’s used in a template, the component rerenders and displays the new value.

There is one use case for @track. When a field contains an object or an array, there’s a limit to the depth of changes that are tracked. To tell the framework to observe changes to the properties of an object or to the elements of an array, decorate the field with @track
Import @api decorator from lwc

@track example

helloWorld.html

<template>
    <lightning-card title="HelloWorld" icon-name="custom:custom14">
      <div class="slds-m-around_medium">
        <p>Hello, {greeting}!</p>
        <lightning-input label="Name" value={greeting} onchange={changeHandler}></lightning-input>
      </div>
    </lightning-card>
</template>

helloWorld.js

import { LightningElement } from 'lwc';
export default class HelloWorld extends LightningElement {
  greeting = 'World';
  changeHandler(event) {
    this.greeting = event.target.value;
  }
}

helloWorld.js-meta.xml

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

@wire

To read Salesforce data, Lightning web components use a reactive wire service. When the wire service provisions data, the component rerenders. Components use @wire in their JavaScript class to specify a wire adapter or an Apex method.

We need to import the @salesforce/apex scoped module into JavaScript controller class.

import apexMethodName from '@salesforce/apex/Namespace.Classname.apexMethodReference';

Here is list of important point of importing apex method:

  • apexMethodName : An imported symbol that identifies the Apex method.
  • apexMethodReference : The name of the Apex method to import.
  • Classname : The name of the Apex class.
  • Namespace—The namespace of the Salesforce organization. Specify a namespace unless the organization uses the default namespace (c), in which case don’t specify it.

 

Call Apex Methods In Lightning web components Example

Apex class AccountHelper

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

We can call the apex class in  Lightning web component using these different ways:

  • Wire a property
  • Wire a function
  • Call a method imperatively

 

Wire a property in lightning Web Component

We can invoke apex method from a component via the wire service. We can @wire a property or a function. Here is the syntax

 
import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';
@wire(apexMethod, { apexMethodParams })
propertyOrFunction;

Lets see example of Wire an Apex Method to a Property

accountListLWC.js

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

accountListLWC.html

 
<template>
    <lightning-card title="Account List From Apex" 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>

accountListLWC.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__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this lwc component on account detail page.

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

We will have following output.

For more details about wire refer to Call Apex Method in LWC

For more details about decorators, please refer to official link.

 

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

System Mode and User Mode in Salesforce

System Mode and User Mode in Salesforce

System Mode and User Mode in Salesforce

System mode means running apex code by ignoring user’s permissions. User mode means running apex code by respecting user’s permissions and sharing of records. Let’s understand it in more detail.

System Mode and User Mode in Salesforce

System Mode

  • System mode means running apex code by ignoring user’s permissions. For example, if logged in user does not have permission to one object but they will able to access that object.
  • In system mode, Apex code has access to all objects and fields permissions, field-level security, sharing rules aren’t applied for the current user. This is to ensure that code won’t fail to run because of hidden fields or objects for a user.
  • In Salesforce, all apex code run in system mode. It ignores user’s permissions. Only exception is anonymous blocks like developer console and standard controllers. Even runAs() method doesn’t enforce user permissions or field-level permissions, it only enforces record sharing.

 

User Mode

  • User mode means running apex code by respecting user’s permissions and sharing of records. For example, if logged in user does not access to objector a record, then they will not be able to access that object..
  • In User mode, Profile level permissions, field-level security, and sharing rules are applied for the current user.
  • In Salesforce, only standard controllers and anonymous blocks like developer console run in user mode.

 

Here is list of all operations in salesforce and their execution mode:

  • Apex Trigger: System Mode
  • Anonymous Apex: User Mode
  • Apex Webservices (SOAP API and REST API) – System
  • Chatter in Apex – User Mode
  • Email Service – User Mode
  • All types of Jobs – System Mode
  • Test method with System.runAs() – User Mode
  • Test method without System.runAs() – System Mode
  • Validation Rule: System Mode
  • Auto-Response Rule – System Mode
  • Assignment Rule: System Mode
  • Workflow Rule: System Mode
  • Escalation Rule: System Mode
  • All Types of calculation behind the formula, Rollup Summary – System Mode
  • Process Builder: System Mode
  • Visual Workflow or flow – User Mode
    • if flow is called from Process Builder – System Mode
    • if flow is called from Workflow – System
    • if flow is called from Apex – (depends on with or without sharing of apex class)
    • if flow is called from Custom Button – System
    • if flow is embed in Visualforce – Depends on VF Page context
    • if flow is called from REST API – System
  • Approval Process – System
  • Publisher Action – System
  • InvocableMethod
    • if this is called from flow – User
    • if this is called from Process Builder (does it depends on with or without sharing is specified on that Class) – System
    • if this is called from REST API – (depends on with or without sharing of the class)
  • Custom Button – System
  • Visualforce Page (StandardController) – User Mode
  • Visualforce Page (StandardController with extension) – System Mode
  • Visualforce Page (Custom Controller)
    • depends on with or without sharing of the controller

 

Here is the order of execution in salesforce salesforce order of execution

Permanent link to this article: https://www.sfdcpoint.com/salesforce/system-mode-and-user-mode-in-salesforce/

Get Record Id in Lightning Component

Get Record Id in Lightning Component

Get Record Id in Lightning Component using  force:hasRecordId

Getting current record id in lightning component or lightning aura component is very easy. We need to add force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the current record.

The current record ID is useful if the component is used on a Lightning record page, as an object-specific custom action or action override in Lightning Experience or the Salesforce app, and so on. This interface has no effect except when used within Lightning Experience, the Salesforce mobile app, and template-based communities. If you are looking for how to get current record id in LWC(Lightning Web component), please refer to Get Record Id in Lightning Web Component. If you are looking for how to get current record id in visualforce page please refer to get current record id salesforce

The recordId attribute is set only when you place or invoke the component in an explicit record context. For example, when you place the component directly on a record page layout, or invoke it as an object-specific action from a record page or object home. In all other cases, such as when you invoke the component as a global action, or create the component programmatically inside another component, recordId isn’t set, and your component shouldn’t depend on it.

Sample Code

<aura:component implements="force:lightningQuickAction,force:hasRecordId">
    <!--More lines here-->
</aura:component>

Get Record Id in Lightning Component Example

Lets create a simple lightning component
CurrentrecordIdExample.cmp

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" access="global" >
    Account Id is {!v.recordId}
</aura:component>

In this example, we are creating a simple lightning component and displaying record id of record and adding it on account record page.

Now we can add this lightning component on account detail page.

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

 

We will get the following output

Get Record Id in Lightning Component

We can also use this component as quick action. For that we need to implement force:lightningQuickAction interface instead of flexipage:availableForRecordHome interface.

For more details please refer to official link.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/get-record-id-in-lightning-component/

Salesforce Summer 20 Release Date

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

Salesforce Summer 20 Release Date calendar

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

If you are looking for top features of summer 20 please refer to Salesforce Summer 20 Release Notes

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

Use Lightning Web Components in Visualforce

Use Lightning Web Components in Visualforce

Use Lightning Web Components in Visualforce

In this post, we will see how we can use LWC in Visualforce Pages or how to display Lightning Web Component In Visualforce Page. Even though the use of lightning is growing day by day, still some customers are using salesforce classic because of many reasons. Sometimes there is a requirement to use lightning web component in visualforce page.

Lightning Web Components for Visualforce is based on Lightning Out, a powerful and flexible feature that lets you embed Lightning web components into almost any web page. When used with Visualforce, some of the details become simpler. For example, you don’t need to deal with authentication, and you don’t need to configure a Connected App. If you are looking for using lightning aura components in visualforce pages, please refer to Use Lightning Components in Visualforce Pages.

In this example, we will see a very basic example of the lightning web component and then display lightning web component in the visualforce page.

helloComponentForVFLWC.html

<template>
    <lightning-card title="Use LWC in Visualforce" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            Hello, This is LWC for visualforce page
        </div>
    </lightning-card>
</template>

helloComponentForVFLWC.js

import { LightningElement } from 'lwc';
export default class HelloComponentForVFLWC extends LightningElement {}

HelloLWCExampleApp.app

Here important point is that ltng:outApp needs to be extended in app.

ltng:outApp adds SLDS resources to the page to allow our Lightning components to be styled with the Salesforce Lightning Design System. If we don’t want SLDS resources added to the page, we need to extend from ltng:outAppUnstyled instead.

<aura:application extends="ltng:outApp" access="GLOBAL">
    <aura:dependency resource="helloComponentForVFLWC" />
</aura:application>

HelloLWCExampleVF.page

<apex:page showHeader="false" sidebar="false">
    <apex:includeLightning />    
    <div id="LightningComponentid" />    
    <script>
    $Lightning.use("c:HelloLWCExampleApp", function() {
        $Lightning.createComponent("c:helloComponentForVFLWC",
          { 
          },
          "LightningComponentid",
          function(cmp) {
             console.log('LWC Componenet added in VF page');
          });
    });
    </script>
</apex:page>

In the above Visualforce page, apex:includeLightning tag imports necessary dependencies and scripts to enable Visualforce to act as Lightning component container.

We can use $Lightning.use() method in JavaScript to refer to Lightning Application which extends ltng:outApp.

We can use $Lightning.createComponent create Lightning Component dynamically.

We can call $Lightning.use() multiple times on a page, but all calls must reference the same Lightning dependency app.

We will get the following output

Use Lightning Web Components in Visualforce

For more detail please refer to official link

Permanent link to this article: https://www.sfdcpoint.com/salesforce/use-lightning-web-components-in-visualforce/

Use Static Resource In LWC(Lightning Web Component)

Use Static Resource In LWC(Lightning Web Component)

Static Resource In LWC

First, Import static resources from the @salesforce/resourceUrl scoped module. Static resources can be archives (such as .zip and .jar files), images, style sheets, JavaScript, and other files.

The syntax for importing static resource in LWC

import myResource from '@salesforce/resourceUrl/resourceReference';

When static resource has namespace

import myResource from '@salesforce/resourceUrl/namespace__resourceReference';
  • myResource—A name that refers to the static resource.
  • resourceReference—The name of the static resource.A static resource name can contain only underscores and alphanumeric characters, and must be unique in your org. It must begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.
  • namespace—If the static resource is in a managed package, this value is the namespace of the managed package.

 

Use Static Resource In Lightning Web Component Example

We will create LWC component to show images. We will get the following output

Use Static Resource In LWC

 

Let’s create static resource with two images, css file and javascript files.

First, create myresource zip file with the following content. It contains images, css and js folder.

myResource content

Go to Setup -> Static resource -> Create New

Create static resource

 

staticResourceLWCExample

<template>
    <lightning-card title="Static Resource Example LWC" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            <img src={spring20Logo}>
            <img src={summer20Logo}>
        </div>
    </lightning-card>
</template>

staticResourceLWCExample

import { LightningElement } from 'lwc';
import My_Resource from '@salesforce/resourceUrl/myResource';
export default class StaticResourceLWCExample extends LightningElement {
    spring20Logo = My_Resource + '/images/salesforce-spring-2020.jpg';
    summer20Logo = My_Resource + '/images/salesfoce-summer-2020.jpeg';
}

staticResourceLWCExample

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

For more details please refer to official link

Permanent link to this article: https://www.sfdcpoint.com/salesforce/use-static-resource-in-lwc/

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/