Workflow in Salesforce

Workflow Rules in Salesforce

What is Salesforce Workflow Rules?

Workflow lets you automate standard internal procedures and processes to save time across your org. A workflow rule is the main container for a set of workflow instructions. These instructions can always be summed up in an if/then statement.

For Example: If you have symptoms of Coronavirus then stay at home.

Workflow rules can be broken into two main components.

  1. Criteria: the “if” part of the “if/then” statement. In other words, what must be true of the record for the workflow rule to execute the associated actions.
  2. Actions: the “then” part of the “if/then” statement. In other words, what to do when the record meets the criteria.

In the example, the criteria is “Have Coronavirus Symptoms” and the action is “Stay At home”. If the criteria isn’t met (No Symptoms), then the action isn’t executed.

Salesforce Workflow Rules

Salesforce Workflow Rules

Create a Workflow Rule

Automate your organization’s standard process by creating a workflow rule.

Demo: https://salesforce.vidyard.com/watch/IqZIFLtEx9rY7AD8QLFE3Q

Create Workflow Rules

Create Workflow Rules

Rule Criteria

Rule Criteria

Add Workflow Criteria

Remember, we are defining ‘IF’ statement criteria using Salesforce Workflow rules and When we need execute this rule.

  1. From Setup, enter Workflow Rules in the Quick Find box, then select Workflow Rules.
  2. Click New Rule.
  3. Choose the object to which you want this workflow rule to apply.
  4. Click Next.
  5. Give the rule a name and description.
  6. Set the evaluation criteria.
    • Created – Evaluate the rule criteria each time a record is created. If the rule criteria is met, run the rule. Ignore all updates to existing records.
    • Created, and every time it’s edited –Evaluate the rule criteria each time a record is created or updated. If the rule criteria are met, run the rule.
    • Created, and any time it’s edited to subsequently meet criteria-(Default) Evaluate the rule criteria each time a record is created or updated.
  7. Enter your rule criteria.
    • Choose criteria are met and select the filter criteria that a record must meet to trigger the rule. For example, set the filter to “Opportunity: Amount greater than 5000” if you want opportunity records with an amount greater than $5,000 to trigger the rule.
    • Choose formula evaluates to true and enter a formula that returns a value of “True” or “False.” Salesforce triggers the rule if the formula returns “True.”
  8. Click Save & Next.

Add Workflow Action

Once you’ve set the criteria for your workflow rule, identify what to do when those criteria are met.

Add an Immediate Action

Immediate actions, like their name suggests, are executed as soon as the workflow rule finishes evaluating the record.

Immediate Action

Immediate Action

  1. Open a workflow rule.
  2. In the Immediate Workflow Actions section, click Add Workflow Action.
  3. Select one of the options to create an action or select an existing one.

 

Below are the Workflow Actions :

  • Email Alert: Email alerts are emails generated by an automated process and sent to designated recipients. These actions consist of the standard text and list of recipients for an email. Refer Email Alert for more details
  • Field Update: Field update actions let you automatically update a field value.  Refer Field Update for more details
  • Flow Trigger: Create a flow trigger so that you can launch a flow from workflow rules. With flow triggers, you can automate complex business processes—create flows to perform logic, and have events trigger the flows via workflow rules—without writing code. For example, your flow looks up and assigns the relevant entitlement for a case.  Refer Flow Trigger for more details
  •  Outbound Message: An outbound message sends information to a designated endpoint, like an external service. You configure outbound messages from Setup. Provide the external endpoint and create a listener for the messages using the SOAP API. You can associate outbound messages with workflow rules, approval processes, or entitlement processes. Refer Outbound Message for more details.
  • Task: Task actions determine the details of an assignment given to a specified user by an automated process. You can associate task actions with workflow rules, approval processes, or entitlement processes. Refer Task for more details.

Add Time-Dependent Action

Time-dependent actions are executed at a specific time, such as 10 days before a record’s close date. When that specific time passes, the workflow rule re-evaluates the record to make sure that it still meets the rule criteria. If the record does, the workflow rule executes those actions.

Time-dependent actions and time triggers are complex features. As you work with time-dependent actions and time triggers, keep in mind their considerations.

If you plan on configuring workflow rules that have time-dependent actions, specify a default workflow user. Salesforce associates the default workflow user with a workflow rule if the user who initiated the rule is no longer active.

Add time Trigger

Add time Trigger

Define Time Trigger

Define Time Trigger

Time Dependent Workflow

Time Dependent Workflow

  1. Open a workflow rule.
  2. In the Time-Dependent Workflow Actions section, click Add Time Trigger.
    NoteNOTE You can’t add a time trigger if:
    • The evaluation criteria is set to Evaluate the rule when a record is: created, and any time it’s edited to subsequently meet criteria.
    • The rule is activated.
    • The rule is deactivated but has pending actions in the workflow queue.
  3. Specify the number of days or hours before or after a date that’s relevant to the record, such as the date the record was created.
    If the workflow rule is still active and valid when this time occurs, the time trigger fires the workflow action.
  4. Save your time trigger.
  5. In the section for the time trigger you created, click Add Workflow Action.
  6. Select one of the options to create an action or select an existing one.
  7. Click Done.

Activate Workflow Rule

Make sure to Active a workflow Rule before start unit testing.

To activate a workflow rule, click Activate on the workflow rule detail page. Click Deactivate to prevent a rule from triggering or if you want to edit the time-dependent actions and time triggers that are associated with the rule.

You can deactivate a workflow rule at any time. However, if you deactivate a rule that has pending actions, Salesforce completes those actions as long as the record that triggered the rule is not updated.

NOTE

  • You can’t delete a workflow rule that has pending actions in the workflow queue. Wait until pending actions are processed, or use the workflow queue to cancel the pending actions.
  • You can’t add time-dependent workflow actions to active workflow rules. Deactivate the workflow rule first, add the time-dependent workflow action, and reactivate the rule.

 

Things to Remember

  1. You can’t delete a workflow rule that has pending actions in the workflow queue. Wait until pending actions are processed, or use the workflow queue to cancel the pending actions.
  2. You can’t add time-dependent workflow actions to active workflow rules. Deactivate the workflow rule first, add the time-dependent workflow action, and reactivate the rule.
  3. TIP Whenever possible, automate your if/then statements with Process Builder instead of workflow rules.
  4. Remember you can also associate an existing action to multiple Workflow rules. Refer Associate Actions to Workflow Rules for more details
  5. Select a Default Workflow User that you want Salesforce to display with a workflow rule when the user that triggered the rule is not active.
    1. From Setup, enter Process Automation Settings in the Quick Find box, then select Process Automation Settings.
    2. For Default Workflow User, select a user.
    3. Save your changes.
  6. You cannot add time-dependent actions to the rule When you select ‘created, and every time it’s edited’ option during the workflow creation,
  7. In workflow Criteria,  You can use merge fields for directly related objects in workflow rule formulas.

 

Happy Learning. Stay home and Stay Safe 🙂

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

Salesforce Winter ’21 Release Notes

Salesforce Winter ’21 Release Notes

All you need to know about Salesforce Winter ’21 Release Notes

Salesforce Winter ’21 Release Notes: We understand that it is difficult and a bit time-consuming to go through the entire release so here we offer to help you learn and grow in the salesforce world by presenting the summary and my most favorite feature of Salesforce Winter’ 21 Release Notes.

Salesforce Winter 21 Release Notes

 

Dynamic Forms

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. This feature, which is now generally available and enabled for everyone, includes some changes since the beta release.

Dynamic forms add field Salesforce Winter 21

Open an existing record page in the Lightning App Builder, then click Upgrade Now from the Record Detail properties pane to launch the Dynamic Forms migration wizard. With only a few clicks, the wizard adds fields and field sections to the page for you.

Dynamic forms upgrade now properties Salesforce Winter 21

Changes Since Beta:

  • Dynamic Forms is now on for everyone in supported editions. The ability to turn it on and off for your org from the Record Page Settings node in Setup is removed.
  • Universally required fields moved to their own section of the palette and have distinctive icons.
  • Packaging is now supported for pages that contain Dynamic Forms components (Field, Field Section).
  • Enhanced support for Dynamic Forms during edit, create, and clone.
  • Several limitations and known issues are resolved.

Scan a Barcode in a Lightning Web Component (Beta)

Use the BarcodeScanner API to add barcode scanning to your Lightning web components. Scan UPC, QR, and other standard barcode types from Lightning components running on a mobile device. Look up product details, record inventory scans, save contact details from a conference badge—your code, your way!

Scan Barcodes on a Mobile Device (Beta)

Interactively Create Engaging Email Templates

Create email templates faster and more easily with visual tools in Email Template Builder. Instead of adding HTML code, your users can drag elements to create effective email templates. They can compose email templates with a few clicks to place design elements right where they want them.

After creating a Lightning email template, users with the correct permission see the Edit in Builder button.

Lightning Email Template Edit Salesforce Winter 21

Click Edit in Builder to open Email Template Builder.

Email Template Builder annotated Salesforce Winter 21

Choose a component (1) and drag it to the canvas (2). Change the details and style of the component using the properties panel (3).

Sales Productivity ETB WIP Salesforce Winter 21

Display Survey Pages Based on Your Data

Let data in your Salesforce org determine which survey page participants view next. Use variables to define conditions in your page branching logic. Use associated record merge field variables and participant record merge field variables to define field-level conditions. Use org variables to define conditions based on your org’s information. Use custom variables to define conditions based on values that you define.

Salesforce Winter 21 survey merge field branching

Auto Add Fields to Custom Report Types

It’s time-consuming to add new custom fields to your reports, especially when you have many custom report types. Now with Auto Add, custom fields that you add to a Salesforce object are added automatically to all the custom report types based on that object. When you create a report from the custom report type, all the custom fields are right there for you to add to your report.

How: From Setup, in the Quick Find box, enter Reports and Dashboards Settings, and then select Reports and Dashboards Settings. Select Auto add new custom fields to custom report type layouts and then click Save.

You can now add new custom fields to a report built from an existing custom report type from the Fields pane in the report builder. All custom fields for the Salesforce object are automatically included in the Fields list, and you can drag any of them to the Columns list.

Salesforce Winter 21 report type auto add fields

Salesforce Anywhere

Salesforce Anywhere is the future experience of CRM — making Salesforce real time. Get alerts about changes to the Salesforce data you care about. Update your Salesforce data in just a few taps with suggested actions. Collaborate in context with chat. Search and view your Salesforce data. And integrate Salesforce Anywhere chat and alerts into your business processes with Lightning Flow and Process Builder.

Salesforce Anywhere Release Notes (Beta)

Find Changed Deals at a Glance

Opportunity deal change highlights help your sales team prioritize work by showing recent changes to amounts and close dates. For example, knowing which deals changed helps sales managers with their weekly coaching sessions. In the opportunities list view and Kanban view, text colors and arrows indicate amounts and close dates that changed during the last 7 days. And users can hover over an arrow to get details.

Salesforce Winter 21 opportunity deal motion end user

How: Opportunity deal change highlights are turned on by default, but you can turn them off (and back on) via Opportunity Settings in Setup.

Salesforce Winter 21 Find Changed Deals at a Glance

Salesforce Lightning Flow

Trigger flows to run when records are deleted. Debug flows as another user, and debug autolaunched flows right in the canvas (beta). Optimize the layout of your flow screens with sections and columns (pilot). Let Flow Builder connect and align elements for you (beta). Launch a record-triggered flow or execute a decision outcome only when the record is updated to meet your criteria. Apply custom logic to record queries and condition requirements throughout your flows.

Shorten Your Visualforce URLs

We’re removing the instance names from Visualforce and other URLs through a release update. The Stabilize URLs for Visualforce, Experience Builder, Site.com Studio, and Content Files update is enforced in Summer ’21.

Customize Components with Lightning Design System Styling Hooks

Lightning Design System Styling Hooks provide you with a set of CSS custom properties so you can customize a component’s look and feel. In Winter ’21, a limited set of CSS custom properties is available for component-level customizations.

As a beta feature, Lightning Design System Styling Hooks is a preview. It isn’t part of the “Services” under your master subscription agreement with Salesforce. Use this feature at your sole discretion, and make your purchase decisions only on the basis of generally available products and features. Salesforce doesn’t guarantee the general availability of this feature within any particular time frame or at all, and we can discontinue it at any time. This feature is for evaluation purposes only, not for production use. It’s offered as-is and isn’t supported, and Salesforce has no liability for any harm or damage arising out of or in connection with it. All restrictions, Salesforce reservation of rights, obligations concerning the Services, and terms for related Non-Salesforce Applications and Content apply equally to your use of this feature. You can provide feedback and suggestions for Lightning Design System Styling Hooks in the IdeaExchange group in the Trailblazer Community.

LWC-Based Template

Build Fast, Efficient Experiences with the LWC-Based Template (Pilot)

Develop communities that load quickly and scale well using the Build Your Own (LWC) template. Based on Lightning Web Components (LWC), a programming model that delivers exceptional performance, this lightweight template supports fully custom solutions. The template, now available as a pilot, includes some changes since the previous release.

We provide the Build Your Own (LWC) template to selected customers through a pilot program that requires agreement to specific terms and conditions. To be nominated to participate in the program, contact Salesforce. Pilot programs are subject to change, and we can’t guarantee acceptance.

Alternatively, you can access a developer preview of the template in Developer editions without signing up for the pilot program. Developer preview participants can create up to 100 sites, whereas pilot participants can create only two.

Regardless of edition, the template isn’t generally available unless or until Salesforce announces its general availability in documentation or in press releases or public statements. We can’t guarantee general availability within any particular time frame or at all. Make your purchase decisions only on the basis of generally available products and features. You can provide feedback and suggestions for the template in the Lightning Web Runtime Communities group in the Trailblazer Community.

For all the features for Winter 21 Release Notes, please refer to the Salesforce website.

Salesforce Winter 21 Release Date

Here’s the new Winter ’21 release schedule:

  • Sandbox preview: The Sandbox Preview window for Winter ’21 begins on September 11, 2020. You must have an active sandbox on a preview instance before then to take advantage of the preview.

Salesforce Winter ’21 Release Date Schedule Calendar

For the Winter ’21 Release, we will upgrade the preview instances to Winter ’21 on September 11 and September 12, 2020, and non-preview instances to Winter ’21 on October 16 and October 17, 2020.

Salesforce Winter 21 release date calendar

Once you locate your current sandbox instance, use the chart below to determine if, when, and what action you should take on your sandbox.

Salesforce Winter 21 Sandbox instance date

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

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

Salesforce Winter 21 Release Date

Salesforce Winter 21 Release Date

Salesforce Winter 21 Release Date

Here is list of key dates for Salesforce Winter 21 Release

  • Pre-Release Org Sign Up:  August 21, 2020
  • Release Notes: August 24, 2020
  • Sandbox Preview Starts: September 11, 2020
  • Release Site: September 11, 2020
  • Release Module: September 11, 2020
  • Release Overview Deck & Feature Matrix: September 14, 2020
  • Release Readiness Live!: September 18, 2020 to September 25, 2020
  • Release Weekends: September 18, October 9, October 16
  • Global Release Webinars: October 2020
  • Release Exam Deadline on Trailhead: April 2021

Please refer to below image.

Salesforce Winter 21 Release Date Key Dates

For more details, please refer source https://trailblazers.salesforce.com/0694S000000ftoM

We will keep updating this article when we will get more information.

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

Lightning Web Components(LWC)Tutorial

Lightning Web Components (LWC)Tutorial

Lightning Web Components-Why, What & Where to start from?

Why Lightning Web Components(LWC)?

AURA framework which was used for current Lightning Components was based on standards of 2014 but are outdated now and it was time for change because for the following reasons:

  • Rendering could be optimized.
  • Standard UI elements were scarce.
  • Lacked modern constructs.
  • Was not fit for modular apps.
  • Web standards were updated.
  • AURA Framework became skill and had its own learning curve.

Additionally, Lightning Web Components(LWC) can coexist and interoperate with Aura components.

Lightning Web Components(LWC) Time To Upgrade

What Lightning Web Components(LWC)?

LWC is a new programming model levering the recent web standards. Rather than being a totally custom and development wise rigid framework, It’s quite flexible. It’s mostly the common Web Standards and a Thin Layer of Specialized services to make it a perfect fit for Modern Rich UI Implementations in Salesforce. This thin layer of specialized services contain Base Lightning Components, Lightning Data Service and User Interface API which work behind the curtain for LWC.

Lightning Web Components(LWC) Benefits

A thin layer of specialized services on top of a standard web stack results in:

  • Ease of development for large scale modular apps. 
  • Ease of Leveraging the latest web functionalities and constructs.
  • A common model and transferable skills.
    (Any web developer working on modern JS frameworks could easily ramp-up LWC).
  • Interoperable components. 
  • Better performance.

 

So, the new development stack looks like:

Lightning Web Components(LWC) Development Stack

Where to start from?

Here are some recommended steps:

  1. Learn more about LWC from the LWC Video Gallery.
  2. Install VS Code and set it up for Salesforce Development.
    You can use ForceCode Extension for Salesforce as it supports LWC Or you can follow this trailhead module.
  3. Get easy to understand sample code for almost all use cases here.
  4. For more samples visit here.
  5. Develop a LWC yourself and try your code by running it here.
  6. Most importantly, Complete the Get Started with LWC trailmix.

 

Lightning Web Components-Component Structure

How is a Lightning Web Component(LWC) formed?

Similar to an AURA component, the main contents of a LWC are also html, javascript. There are optional content like css. But then in addition to these for LWC, an xml configuration file is also included which defines the metadata values for the component.
So, a LWC component would look like:

Lightning Web Components(LWC) Structure

Lightning Web Components(LWC) Structure VS Code

Now, lets cover a brief overview of these files one by one:

HTML

  • Has a root tag <template> which contains your component’s HTML. 
  • When renders, the <template> tag is replaced with <namespace-component-name>.

Lightning Web Components(LWC) HTML file

 

Javascript

  • Import functionality declared in a module eg-lwc(the core module), use the import statement. 
  • To allow other code to use functionality in a module, use the export statement.
  • LightningElement is custom wrapper of the standard HTML element and we extend it in the component and export.

Lightning Web Components(LWC) JS File

 

Configuration

XML file that defines the metadata configuration values for the component eg-

  • Components Label
  • Availability
  • Configuration Attributes
  • Builder Attributes

Lightning Web Components(LWC) Config file

 

CSS

  • To style a component. 
  • The style sheet is applied automatically.


Lightning Web Components(LWC) CSS File

 

So, the files that we have discussed how would the component build with these look?

Component UI

Lightning Web Components(LWC) UI

Summary

This is the best time to learn and start early with Lightning Web Components, which offer the latest web standards, delivers unprecedented performance and productivity and interoperate seamlessly with existing code.

Example of Lightning Web Components(LWC)

Here is list of some of Lightning Web Component example for developers:

Get Record Id in Lightning Web Component

lightning-record-view-form

Call Apex Methods In Lightning web components

Lightning Web Component lightning-datatable

Use Lightning Web Components in Visualforce

Modal/Popup Lightning Web Component(LWC)

Custom Labels In Lightning Web Component(LWC)

Lightning Web Component(LWC) Toast Messages

Lightning Spinner in LWC (Lightning Web Component)

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

lightning-record-form LWC

template if:true Conditional Rendering LWC

for:each template directives in LWC

Navigation Service in LWC(Lightning Web Components)

Wrapper Class in LWC(Lightning Web Component)

Use Static Resource In LWC(Lightning Web Component)

Decorators in Lightning Web Component(LWC)

File Upload in Lightning Web Component(lwc)

lightning-card LWC

wire Service LWC Lightning Web Component

Good luck. Happy Coding 🙂

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

wire Service LWC Lightning Web Component

wire Service LWC Lightning Web Components(LWC)

@wire Service LWC

Lightning web components(LWC) use a reactive wire service, which is built on Lightning Data Service. Components use @wire in their JavaScript class to read data from one of the wire adapters in the lightning/ui*Apimodules and also to call the apex controller server-side methods using wire services. The wire service provisions an immutable stream of data to the component. Each value in the stream is a newer version of the value that precedes it.

We call the wire service reactive in part because it supports reactive variables, which are prefixed with $. If a reactive variable changes, the wire service provisions new data. We say “provisions” instead of “requests” or “fetches” because if the data exists in the client cache, a network request may not be involved. The wire service delegates control flow to the Lightning Web Components engine. Delegating control is great for read operations, but it isn’t great for create, update, and delete operations. As a developer, you want complete control over operations that change data. That’s why you perform create, update, and delete operations with a JavaScript API instead of with the wire service.

Wire Service Syntax

Import a wire adapter using named import syntax.

import { wire} from 'lwc';

Decorate a property or function with @wire and specify the wire adapter.

@wire(adapterId, adapterConfig)
propertyOrFunction;

Here is full code syntax and its detail for using wire

import { wire} from 'lwc';
@wire(adapterId, adapterConfig)
propertyOrFunction;
  • adapterId (Identifier)—The identifier of the wire adapter.
  • adapterModule (String)—The identifier of the module that contains the wire adapter function, in the format namespace/moduleName. Look at the format! To import a module in JavaScript, use lightning/ui*Api instead of lightning-ui-*-api.
  • adapterConfig (Object)—A configuration object specific to the wire adapter. Configuration object property values can be either strings or references to objects and fields imported from @salesforce/schema. Properties in the adapterConfig object can’t be undefined. If a property is undefined, the wire service doesn’t provision data. Don’t update a wire adapter configuration object property in renderedCallback() as it can result in an infinite loop.
  • propertyOrFunction—A private property or function that receives the stream of data from the wire service. If a property is decorated with @wire, the results are returned to the property’s data property or error property. If a function is decorated with @wire, the results are returned in an object with a data property and an error property.

 

Import References to Salesforce Objects and Fields

When you use a wire adapter in a lightning/ui*Api module, we strongly recommend importing references to objects and fields. Salesforce verifies that the objects and fields exist, prevents objects and fields from being deleted, and cascades any renamed objects and fields into your component’s source code. It also ensures that dependent objects and fields are included in change sets and packages. Importing references to objects and fields ensures that your code works, even when object and field names change.

If a component isn’t aware of which object it’s using, use strings instead of imported references. Use getObjectInfo to return the object’s fields. All wire adapters in the lightning/ui*Api modules respect object CRUD rules, field-level security, and sharing. If a user doesn’t have access to a field, it isn’t included in the response.

To import a reference to an object, use this syntax.

import objectName from '@salesforce/schema/object';
import objectName from '@salesforce/schema/namespace__object';

import POSITION_OBJECT from '@salesforce/schema/Position__c';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';

 

To import a reference to a field, use this syntax.

import FIELD_NAME from '@salesforce/schema/object.field';

import POSITION_LEVEL_FIELD from '@salesforce/schema/Position__c.Level__c';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';

 

To import a reference to a field via a relationship, use this syntax. You can use relationship fields to traverse to parent objects and fields. You can specify up to three relationship fields, which results in four objects and the field being referenced. For example, Opportunity.Account.CreatedBy.LastModifiedById returns 4 levels of spanning fields.

import SPANNING_FIELD_NAME from '@salesforce/schema/object.relationship.field';

import POSITION_HIRINGMANAGER_NAME_FIELD__c from '@salesforce/schema/Position__c.HiringManager__r.Name__c';
import ACCOUNT_OWNER_NAME_FIELD from '@salesforce/schema/Account.Owner.Name';

 

This code imports the Account.Name field and uses it in a wire adapter’s configuration object.

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';

export default class Record extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: [ACCOUNT_NAME_FIELD] })
    record;
}

This code is almost identical, but it uses a string to identify the Account.Name field. This code doesn’t get the benefits that you get from importing a reference to the field.

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

export default class Record extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: ['Account.Name'] })
    record;
}

Mark a Configuration Object Property as Dynamic and Reactive

n the wire adapter’s configuration object, prefix a value with $ to reference a property of the component instance. The $ prefix tells the wire service to treat it as a property of the class and evaluate it as this.propertyName. The property is reactive. If the property’s value changes, new data is provisioned and the component rerenders.

In this example, $recordId is dynamic and reactive.

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
const FIELDS = [
    'Contact.Name',
    'Contact.Title',
    'Contact.Phone',
    'Contact.Email',
];
export default class WireGetRecordDynamicContact extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: FIELDS })
    contact;
    get name() {
        return this.contact.data.fields.Name.value;
    }
    get title() {
        return this.contact.data.fields.Title.value;
    }
    get phone() {
        return this.contact.data.fields.Phone.value;
    }
    get email() {
        return this.contact.data.fields.Email.value;
    }
}

Decorate a Property with @wire

Wiring a property is useful when you want to consume the data or error as-is.

If the property decorated with @wire is used as an attribute in the template and its value changes, the wire service provisions the data and triggers the component to rerender. The property is private, but reactive.

This code applies @wire to the record property.

import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';
export default class Record extends LightningElement {
    @api recordId;
    @wire(getRecord, { recordId: '$recordId', fields: [ACCOUNT_NAME_FIELD] })
    record;
}

Decorate a Function with @wire

Wiring a function is useful to perform logic whenever new data is provided or when an error occurs. The wire service provisions the function an object with error and data properties, just like a wired property.

The function is invoked whenever a value is available, which can be before or after the component is connected or rendered.

wire Service LWC Example by decorating a Function with @wire

wireFunctionLWC.js

// WireFunctionLWC.js
import { LightningElement, api, track, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
export default class WireFunctionLWC extends LightningElement {
    @api recordId;
    @track record;
    @track error;
    @wire(getRecord, { recordId: '$recordId', fields: ['Account.Name'] })
    wiredAccount({ error, data }) {
        if (data) {
            this.record = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.record = undefined;
        }
    }
    get name() {
        return this.record.fields.Name.value;
    }
}

wireFunctionLWC.html

template>
    <lightning-card title="Wire Function" icon-name="standard:account">
        <template if:true={record}>
            <div class="slds-m-around_medium">
                <p>{name}</p>
            </div>
        </template>
        <template if:true={error}>
            {error}
        </template>
    </lightning-card>
</template>

wireFunctionLWC.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 detail page.

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

We will have the following output.

wire Service LWC

 

Call Apex Methods using wire

Lightning web components can import methods from Apex classes into the JavaScript classes. Once after importing the apex class method you can able call the apex methods as functions into the component by calling either via the wire service or imperatively. The Apex Method should be marked with @AuraEnabled. Before you use an Apex method, make sure that there isn’t an easier way to get the data. See whether a base Lightning component, like lightning-record-form, lightning-record-view-form, or lightning-record-edit-form works for your use case. If they don’t give you enough flexibility, use a wire adapter like getListUi or getRecordUi. And if you can’t use a wire adapter, write an Apex method.

Apex wire Import Syntax

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.

 

For more details refer to Call Apex Methods In Lightning web components

Most of the information in this article is copied from the official link. For more details about wire Service LWC please refer official link.

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

lightning-card LWC

lightning-card LWC (Lightning Web Component)

lightning-card LWC (Lightning Web Component)

A lightning-card is used to apply a stylized container around a grouping of information. The information could be a single item or a group of items such as a related list.

Use the variant or class attributes to customize the styling.

A lightning-card contains a title, body, and footer. To style the card body, use the Lightning Design System helper classes.

When applying Lightning Design System classes or icons, check that they are available in the Lightning Design System release tied to your org. The latest Lightning Design System resources become available only when the new release is available in your org.

lightning-card LWC Example

We will create LWC component using lightning-card. We will get the following output

lightning-card LWC (Lightning Web Component)

 

lightningCardLWC.js

<template>
    <lightning-card
            variant="narrow"
            icon-name="standard:opportunity">
        <h1 slot="title">Hello title</h1>
        <p class="slds-p-horizontal_small">This is body. You can have your content here</p>
        <div slot="actions">
            <lightning-button label="New" slot="actions"></lightning-button>
        </div>
        <div slot="footer">
            <p>Contact Us SFDCPoint</p>
        </div>
    </lightning-card>
</template>

lightningCardLWC.js

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

lightningCardLWC.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 lightningCardLWC component and drag it on page.
  • Click Save and activate.

Usage Considerations

Icons are not available in Lightning Out, but they are available in Lightning Components for Visualforce and other experiences.

title is available as an attribute or a slot. Pass in the title as a slot if you want to pass in additional markup, such as making the title bold. Or use the title attribute if your title does not need extra formatting. Setting the title attribute overwrites the title slot.

There is one more practical example of using lightning-card, please refer to Lightning Spinner in LWC

For more details please refer to official link

For LWC lightning-card example please refer to this link

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

Visual Studio Code Keyboard Shortcuts

Visual Studio Code Keyboard Shortcuts

Visual Studio Code Keyboard Shortcuts

Visual Studio Code is the go-to code editor for Salesforce developers. It’s free, open-source, and available for Windows, Linux, and macOS. This editor has easy-to-install extensions for syntax highlighting, code completion, and more. Visual Studio Code can be used with many programming languages. Here in this post, we will see some keyboard shortcuts for visual studio code which might help in increasing productivity for developers.

Visual Studio Code Keyboard Shortcuts

Here is list of VS Code Keyboard Shortcuts:

  • To Show Command Palette: Ctrl+Shift+P, F1
  • To Open or Go to File: Ctrl+P
  • New visual code window or instance: Ctrl+Shift+N
  • To Close window or instance: Ctrl+Shift+W
  • To open User Settings: Ctrl+,
  • To open Keyboard Shortcuts: Ctrl+K Ctrl+S
  • Cut line (empty selection): Ctrl+X
  • Copy line (empty selection): Ctrl+C
  • Move line up/down: Alt+ ↑ / ↓
  • Copy line up/down: Shift+Alt + ↓ / ↑
  • Delete Line: Ctrl+Shift+K
  • Insert line below: Ctrl+Enter
  • Insert line above: Ctrl+Shift+Enter
  • Add line comment: Ctrl+K Ctrl+C
  • Remove line comment: Ctrl+K Ctrl+U
  • Toggle line comment: Ctrl+/
  • Toggle block comment: Shift+Alt+A
  • Go to Line…: Ctrl+G
  • Find: Ctrl+F
  • Find next/previous: F3 / Shift+F3
  • Select all occurrences of Find match: Alt+Enter

 

Here is VS Code Keyboard Shortcuts for Windows, Mac and linux

Command ActionWindows keyboard ShortcutMac keyboard ShortcutLinux keyboard Shortcut
To Show Command PaletteCtrl+Shift+P, F1⇧⌘P, F1Ctrl+Shift+P, F1
To Open or Go to FileCtrl+P⌘PCtrl+P
New visual code window or instanceCtrl+Shift+N⇧⌘NCtrl+Shift+N
To Close window or instanceCtrl+Shift+W⌘WCtrl+Shift+W
To open User SettingsCtrl+,⌘,Ctrl+,
To open Keyboard ShortcutsCtrl+K Ctrl+S⌘K ⌘SCtrl+K Ctrl+S
Cut line (empty selection)Ctrl+X⌘XCtrl+X
Copy line (empty selection)Ctrl+C⌘CCtrl+C
Move line up/downAlt+ ↑ / ↓⌥↓ / ⌥↑Alt+ ↑ / ↓
Copy line up/downShift+Alt + ↓ / ↑⇧⌥↓ / ⇧⌥↑Shift+Alt + ↓ / ↑
Delete lineCtrl+Shift+K⇧⌘KCtrl+Shift+K
Insert line belowCtrl+Enter⌘EnterCtrl+Enter
Insert line aboveCtrl+Shift+Enter⇧⌘EnterCtrl+Shift+Enter
Add line commentCtrl+K Ctrl+C⌘K ⌘CCtrl+K Ctrl+C
Remove line commentCtrl+K Ctrl+U⌘K ⌘UCtrl+K Ctrl+U
Toggle line commentCtrl+/⌘/Ctrl+/
Toggle block commentShift+Alt+A⇧⌥AShift+Alt+A
Go to Line...Ctrl+G⌃GCtrl+G
FindCtrl+F⌘FCtrl+F
ReplaceCtrl+H⌥⌘FCtrl+H
Find next/previousF3 / Shift+F3⌘G / ⇧⌘GF3 / Shift+F3
Select all occurrences of Find matchAlt+Enter⌥EnterAlt+Enter
Add selection to next Find matchCtrl+D⌘DCtrl+D
Move last selection to next Find matchCtrl+K Ctrl+D⌘K ⌘DCtrl+K Ctrl+D
Select current lineCtrl+I⌘ICtrl+I
Select all occurrences of current selectionCtrl+Shift+L⇧⌘LCtrl+Shift+L
Close editorCtrl+F4, Ctrl+W⌘WCtrl+W
Close folderCtrl+K F⌘K FCtrl+K F
New FileCtrl+N⌘NCtrl+N
Open File...Ctrl+O⌘OCtrl+O
SaveCtrl+S⌘SCtrl+S
Save As...Ctrl+Shift+S⇧⌘SCtrl+Shift+S
Save AllCtrl+K S⌥⌘SCtrl+K S
Close / Close AllCtrl+F4 / Ctrl+K Ctrl+W⌘W / ⌘K ⌘WCtrl+W / Ctrl+K Ctrl+W
Toggle full screenF11⌃⌘FF11
Show SearchCtrl+Shift+F⇧⌘FCtrl+Shift+F
Show ExtensionsCtrl+Shift+X⇧⌘XCtrl+Shift+X
Replace in filesCtrl+Shift+H⇧⌘HCtrl+Shift+H
Show Output panelCtrl+Shift+U⇧⌘UCtrl+K Ctrl+H

 

VS Code shortcuts

vs code comment shortcut

In vscode many time we have to comment/uncomment the line of code or block of code from time to time. We can select a block of code and use the key sequence Ctrl+K+C, it will comment out the section of code.  Ctrl+K+U will uncomment the code. It will be a line comment. For Block Comment, we can select lines of code and use Shift+Alt+A. It will toggle comments on and off. You can mac shortcut for same in above table.

VS Code Navigate Forward/Backward Ctrl+–/Ctrl+Shift+–

When we have multiple files open at the same time, we might need a way to quickly move back and forth between two or three different locations in your code. If we have moved from one location to another we can use the keyboard sequence Ctrl+– to move to the previous location and then you can return using Ctrl+Shift+–.

VS Code Open Command Palette

Ctrl+Shift+P : The command palette is very useful in VS Code. We can simply use Ctrl+Shift+P in windows and ⇧⌘P(Command + Shift+ P) for mac to open command Palette.

VS Code Go To Line

To go to a line in the file, you use ctrl + g, then type a line number. Alternatively, you can also open the go-to file menu with command + p first. Then type :. Then type your line number. In mac shortcut is ⌃G

VS Code Search in all Files

Searching  in all files is very useful and used very frequently by developers. Search all Windows Shortcut is Ctrl+Shift+F. Search all Mac shortcut is ⇧⌘F(Command+Shift+F).

For more details please refer to official link

Permanent link to this article: https://www.sfdcpoint.com/salesforce/visual-studio-code-keyboard-shortcuts/

Developing a Robust Salesforce Testing Strategy

Developing a Robust Salesforce Testing Strategy

Developing a Robust Salesforce Testing Strategy

Salesforce testing is an important requirement to keep the performance of applications as expected. However, they need to undergo a robust testing strategy comprising unit testing, performance testing, UAT testing, and functional testing, among others. 

Developing a Robust Salesforce Testing Strategy

 

Quality remains the fundamental element in the success of any organization, let alone a digital one. With digital technology playing a discerning role in improving the quality of our lives, ensuring the quality of such technology is of primary importance. This calls for software application testing and fixing the bugs early in the development (and testing) cycle. The enterprises of today are increasingly using CRM or ERP solutions to manage operations and other processes seamlessly. Salesforce is one such CRM software suite, which along with SAP, Oracle, and Microsoft, is witnessing a steady growth in its adoption. The reasons for the popularity of Salesforce can be attributed to its ease of customization, implementation, flexibility, and scalability. Further, Salesforce is leveraged by the industry in managing leads, contacts, clients, and opportunities. However, not everything is hunky-dory when it comes to implementing the software. For starters, everyone’s concurrence is necessary and the objectives of business need to be clearly defined. Thereafter comes Salesforce testing.

Why test Salesforce?

Since codes can play a critical role in integrating various business processes and functions within an organization, they need to be tested for Salesforce. Salesforce testing would ensure the underlying codes are performing, reliable, and qualitatively superior. The test validates the customizations and configurations done to the software to develop a quality product. The product in the form of software ought to support the client’s business processes. There are two types of testing in a Salesforce testing framework – manual and automated.

In manual Salesforce testing, the application is tested manually with focus on regression, system, integration, and functional testing. However, Salesforce automation testing is about validating the software using a test tool like Selenium. 

How to develop a robust Salesforce testing

A business needs to work on automating salesforce application testing to get the best results. However, the steps to validate the applications developed on Salesforce are as follows: 

  • Business objective: The various CRM features of Salesforce should be aligned with the business objectives. The main purpose of developing and implementing a tool on Salesforce should be understood by the testers. To cite an example, by knowing the purpose of automating the sales process, one can formulate a robust testing strategy. 
  • Test case scenarios: While creating a Salesforce testing framework make a list of the possible test case scenarios and exceptions. The list should also contain the expected outcomes for each test case scenario and action. Based on the same, the test data need to be collated for each scenario. 
  • Test drive: The Salesforce platform comes with a program called ‘pre-release trial,’ which allows the testing of any application before entering the production area. Since this is not linked to the production area there would not be any danger of manipulating the real-time data. This gives an ideal opportunity to check various applications if they meet the expected outcomes. 
  • Functional testing: To ensure maximum test coverage and enhance the quality of the code, testers should go for rigorous Salesforce functional testing. This will help them validate various functions from the users’ perspective.
  • Test management:While conducting tests, the testers should ensure the application, function, or feature is in alignment with the operations or business objectives. Therefore, the test results should be checked against the reference data to ensure quality. 
  • UAT testing: With Salesforce automated testing, care should be taken to conduct User Acceptance Testing (UAT). This way glitches or vulnerabilities inherent in the software can be identified and fixed before the software is released into the market.
  • Maintaining test records: This is the most crucial aspect of Salesforce testing as it offers stakeholders a dashboard to understand any underlying issues with the software. Whether it is Salesforce automation testing or manual testing, test records help administrators to identify, understand, and mitigate risks. The records document various failure scenarios and help in further escalation to responsible persons to fix the issues.

 

Conclusion about Salesforce Testing

Implementing a successful test strategy for Salesforce can help businesses to identify the bottlenecks or glitches and streamline their operations. Since a lot is at stake, the applications developed on the platform should be thoroughly tested for various parameters. It is only after following a successful Salesforce testing that organizations can remain competitive. 

For more details about salesforce test class please refer to test class in Salesforce.

Permanent link to this article: https://www.sfdcpoint.com/salesforce/developing-a-robust-salesforce-testing-strategy/

File Upload in Lightning Web Component(lwc)

File Upload in Lightning Web Component(lwc)

File Upload in Lightning Web Component(lwc)

lightning-file-upload component provides an easy and integrated way for users to upload multiple files. The file uploader includes drag-and-drop functionality and filtering by file types.

File uploads are always associated to a record, so the record-id attribute is required. Uploaded files are available in Files Home under the Owned by Me filter and on the record’s Attachments related list that’s on the record detail page. Although all file formats that are supported by Salesforce are allowed, you can restrict the file formats using the accept attribute.

lightning-file-upload component inherits styling from file selector in the Lightning Design System.

LWC file upload Example

fileUploadLWC.html

<template>
    <lightning-card title="LWC File Upload Example" icon-name="custom:custom19">
        <lightning-file-upload
            label="Attach receipt"
            name="fileUploader"
            accept={acceptedFormats}
            record-id={recordId}
            onuploadfinished={handleUploadFinished}
            multiple>
    </lightning-file-upload>
    </lightning-card>
</template>

fileUploadLWC.js

import { LightningElement, api } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class FileUploadLWC extends LightningElement {
    @api recordId;
    get acceptedFormats() {
        return ['.pdf', '.png','.jpg','.jpeg'];
    }
    handleUploadFinished(event) {
        // Get the list of uploaded files
        const uploadedFiles = event.detail.files;
        let uploadedFileNames = '';
        for(let i = 0; i < uploadedFiles.length; i++) {
            uploadedFileNames += uploadedFiles[i].name + ', ';
        }
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success',
                message: uploadedFiles.length + ' Files uploaded Successfully: ' + uploadedFileNames,
                variant: 'success',
            }),
        );
    }
}

fileUploadLWC.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 detail page.

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

 

We will get the following output where the user will be able to upload multiple files on the account record.

File Upload in Lightning Web Component

 

Once the user will click on Done, user will see a success message.

LWC File Upload Success Message

File Upload Limits

By default, you can upload up to 10 files simultaneously unless your Salesforce admin has changed that limit. The org limit for the number of files simultaneously uploaded is a maximum of 25 files and a minimum of 1 file. The maximum file size you can upload is 2 GB. In Communities, the file size limits and types allowed follow the settings determined by community file moderation. By default, guest users can’t upload files. You can enable the org preference. Allow site guest users to upload files.

Usage Considerations

This component is not supported in Lightning Out or standalone apps, and displays as a disabled input. Additionally, if the Don’t allow HTML uploads as attachments or document records security setting is enabled for your organization, the file uploader cannot be used to upload files with the following file extensions: .htm, .html, .htt, .htx, .mhtm, .mhtml, .shtm, .shtml, .acgi, .svg.

For more details please refer to official link. This example is copied from this official link with small tweaks.

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

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/