Post 2 – Communicate Between Salesforce Lightning Web Components: Parent to Child

This is the latest series of posts I am doing on a new Pluralsight course I created titled, “Communicate Between Salesforce Lightning Web Components”.

Working with Public Properties

Public properties can be used to pass data from a parent component to one or more children components. For Lightning Web Components (LWC), data is passed from the parent to the child using the @api decorator.

Parent to Child Communication
Parent to Child Communication

Decorators are used in JavaScript to wrap one piece of code with another. That is why they are called decorators. The @ symbol is placed before the name of the decorator and for LWC the @api decorator is a special decorator used to expose public properties or methods.

When used with a property, these properties/fields are reactive. This means whenever the value of the property changes, the component is automatically rerendered. For this reason, each property can be associated with only one decorator. This also applies when a method is decorated.

Displaying Products

In this post, I will be working with nested components used to search for and display products. The parent or container component will be named displayProducts. The code for this component is seen below:

<!-- displayProduct.html -->

<template>
    <div class="slds-card slds-var-p-around_x-small">
        <lightning-input
            label="Search Key"
            type="text"
            onchange={handleSearchKeyChange}
            class="search-bar"
        ></lightning-input>
        <template if:true={products.data}>
          <template if:true={products.data.length}>
             <div class="content">
                <template for:each={products.data}
                     for:item="product">
                     <!-- Product Tile Component here-->
                     <c-product-tile
                        key={product.Id}
                        product={product}
                        onselected={handleProductSelected}
                        class="slds-var-m-around_x-small">
                     </c-product-tile>
                 </template>
              </div>
            </template>
            <template if:false={products.data.length}>
                <p>No products matching your selection</p>
            </template>
        </template>
        <template if:true={products.error}>
            <p>Error when getting product data</p>
        </template>
    </div>
</template>


// displayProducts.js

import { LightningElement, wire } from 'lwc';

import { publish, MessageContext } from 'lightning/messageService';
import PRODUCT_SELECTED_MESSAGE from '@salesforce/messageChannel/ProductSelected__c';

// getProducts() method in ProductController Apex class
import getProducts from '@salesforce/apex/ProductController.getProducts';

export default class DisplayProducts extends LightningElement {

    searchKey = '';     
    
    // Load context for Lightning Messaging Service 
    @wire(MessageContext) messageContext;

    //Publish ProductSelected message
    handleProductSelected(event) {  
        publish(this.messageContext, PRODUCT_SELECTED_MESSAGE, {
            productId: event.detail
        });
    }

    // Load the list of available products.
    @wire(getProducts, { searchKey: '$searchKey' })
    products;

    handleSearchKeyChange(event) {
        this.searchKey = event.target.value.toLowerCase();
    }

}

Things to notice in the bolded portion of the displayProducts.html file above:

  1. Since a search may return multiple products, a child component named productTile will be used to display just one product as a tile.
  2. An iterator will be used to display as many instances of this child component as there are records returned.
  3. I am passing the product id through the key attribute and the actual product data through the product attribute.

Here is the HTML and JS for the productTile component.

<!-- producTile.html -->

<template>
  <a onclick={handleClick}>
    <div class="content">
      <img
         src={pictureUrl}
         class="product slds-align_absolute-center"
         alt="Product picture"
      />
      <div>
         <p class="title slds-align_absolute-center">{name}</p>
         <p class="slds-align_absolute-center">
            MSRP:&nbsp;
            <lightning-formatted-number
               format-style="currency"
               currency-code="USD"
               value={msrp}
               class="price"
               maximum-fraction-digits="0">
            </lightning-formatted-number>
         </p>
      </div>
    </div>
  </a>
</template>


// productTile.js

import { LightningElement, api } from 'lwc';

export default class ProductTile extends LightningElement {

    _product;
    pictureUrl;
    name;
    msrp;


    @api
    get product() {
        return this._product;
    }
    set product(value) {
        this._product = value;
        this.pictureUrl = value.Picture_URL__c;
        this.name = value.Name;
        this.msrp = value.MSRP__c;
    }

    handleClick() {
        const selectedEvent = new CustomEvent('selected', {
            detail: this.product.Id
        });
        this.dispatchEvent(selectedEvent);
    }


}

Things to notice in the bolded portion of the productTile.js file above:

  1. api was added to the list of modules to be imported.
  2. Below that will be private variables used for the product data passed from the parent component.
  3. Data will be passed to the child through getter and setter functions, which need to be annotated with the @api decorator, in order to make them public.

The end result of all of this is a component that looks like this:

Final rendered version of the displayProducts component with child productTile component
Final rendered version of the displayProducts component with child productTile component

The code and explanations in this post is just a sample of all that is covered in the Pluralsight course, Communicate Between Salesforce Lightning Web Components”. Check that out if you are interested in learning more about how LWC’s communicate.

New Course on Salesforce Security: Getting Started

Salesforce Security: Getting Started is the first in a series that is dedicated to helping you prepare for the Salesforce Certified Sharing and Visibility Designer exam. This course is designed to take you beyond just learning the necessary facts and give you real-world scenarios that should help prepare you on your journey towards certification.

The company at the center of this course is Globomantics, a fictional global robotics provider. They are also a new Salesforce Enterprise customer with over 20,000 employees located across the globe.

Globomantics is using Field Service Lightning to help their employees provide world-class customer service. They have hired a Solution architect to help them design a secure and scalable sharing architecture on Salesforce.

In this course, you will learn how to evaluate and configure object, field-level, role and security settings that provide access to the platform. When you’re finished, you will have the skills and knowledge to declaratively provide high-level data access to the relevant people in your Salesforce organization.

Record sharing, which is a very complex area will not be covered until the next course in this series. But that should be coming out in the next month. Stay tuned for that announcement.

Post 1 – Communicate Between Salesforce Lightning Web Components: Child to Parent

This is the latest series of posts I am doing on a new Pluralsight course I created titled, “Communicate Between Salesforce Lightning Web Components”.

Communicating With Events

In this post, I will be covering the different ways nested lightning web components can communicate from the child to the parent using custom events.

Child to Parent Component Relationship

Custom events are used to communicate up the component hierarchy. They allow a child to communicate with it’s parent component.

Even though they are based on a web standard, Lightning Web Components offer a CustomEvent interface to create and dispatch these events.

For simple events, in which no data needs to be passed to the parent component, the custom event can be created and dispatched with a single line of code, such as what you see below:

handleClick() {
	 this.dispatchEvent(new CustomEvent('clicked'));
}

The event type, which in this example is “clicked” is required. It should also follow the DOM event naming standard. This means there should be no uppercase letters or spaces. If two words are used, they should be separated with an underscore.

Child to Parent Example

I am going to show you a nested component scenario and point out the important things to consider. In this scenario the children will not be able to communicate with each other. They will only communicate with their parent component. I will also use Lightning App Builder to create a one-region app page to host this parent component. The end result will look like the following:

Simple Child to Parent Communication
Simple Child to Parent Communication

Parent Component Code

In this example, there will be a parent component that will act as a container component and nested inside of it will be two children components named child and child2.

<!-- parent.html -->

<template>
    <lightning-card 
        title="Child to Parent Communication" 
        icon-name="utility:people">
        <lightning-layout vertical-align="start">
            <lightning-layout-item padding="around-small" size="6">
                <div class="slds-box_small">
                    <b>Event Name:</b>
                    <lightning-formatted-text 
                        class="slds-m-left_small" 
                        value={eventName}>
                    </lightning-formatted-text>
                    <div class="slds-box slds-m-around_small">
                        <c-child onclicked={handleButtonClicked}></c-child>
                     </div>
                </div>
            </lightning-layout-item>
            <lightning-layout-item padding="around-small" size="6">
                <div class="slds-box_small">
                    <b>Event Name:</b>
                    <lightning-formatted-text 
                        class="slds-m-left_small" 
                        value={eventName2}>
                    </lightning-formatted-text>
                    <div class="slds-box slds-m-around_small">
                        <c-child2 onclicked2={handleButtonClicked2}></c-child2>
                    </div>
                </div>
            </lightning-layout-item>
      </lightning-layout>
    </lightning-card>
</template>
//parent.js

import { LightningElement } from 'lwc';

export default class Parent extends LightningElement {
    eventName;
    eventName2;

    handleButtonClicked2(event) {
       //this.eventName2 = 'Child2 Button Clicked: ' + event.detail;
       this.eventName2 = 'Child2 Button Clicked: ' + 
            event.detail.ename + event.detail.num;
    }

    handleButtonClicked(event) {
        this.eventName = 'Child Button Clicked';
    }
    
}
<!-- parent.js.meta.xml-->

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <masterLabel>LWC Events</masterLabel>
    <description>This is a component demonstrating how child to parent event relationship works</description>
    <targets>
        <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>

Simple Child Component

This child component will use an inline event handler to simply pass a notification to the parent that a button has been clicked inside the child. There is not much to say about this method since it is very straight forward.

<!-- child.html -->

<template>
    <lightning-card title="Simple Child Component">
        <lightning-layout vertical-align="start">
            <lightning-layout-item padding="around-small" size="12">
                <lightning-button 
                    variant="brand" 
                    label="Fire Event from Simple Child" 
                    onclick={handleClick} 
                    class="slds-m-around_small">
                </lightning-button> 
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>
// child.js

import { LightningElement } from 'lwc';

export default class Child extends LightningElement {
    
    handleClick() {
        this.dispatchEvent(new CustomEvent('clicked'));
    }

}

Child Component Passing Data

The child2 component will be more complex since it will pass multiple data elements from the child to the parent component. The first input data field can be used to enter a text-based field and the second one allows the user to enter a number. The values for both data fields will be concatenated together and displayed as an event name in the parent component.

<!-- child2.html -->

<template>
    <lightning-card title="Complex Child Component">
        <lightning-layout vertical-align="start">
            <lightning-layout-item padding="around-small" size="12">
                <lightning-input 
                    type="text" 
                    name="inName" 
                    label="Enter a name:" 
                    class="slds-m-around_small"
                    onchange={handleNameChange}>
                </lightning-input>
                <lightning-input 
                    type="number" 
                    name="inNumber" 
                    label="Enter a number:" 
                    class="slds-m-around_small"
                    onchange={handleNumberChange}
                    placeholder="2">
                </lightning-input>
                <lightning-button 
                    variant="brand" 
                    label="Fire Event from Complex Child" 
                    onclick={handleClick} 
                    class="slds-m-around_small">
                </lightning-button> 
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>
// child2.js

import { LightningElement } from 'lwc';

export default class Child2 extends LightningElement {
    eventNumber = 0;
    copiedObject;
    eventObject = {
        num : 0,
        ename: ''
    };

    handleNumberChange(event) {
        this.eventObject.num = event.detail.value;
    } 

    handleNameChange(event) {
        this.eventObject.ename = event.detail.value;
    } 

    handleClick() {
        // Make a shallow copy into new object
        this.copiedObject = Object.assign({}, this.eventObject);
        this.dispatchEvent(
            new CustomEvent('clicked2', { detail: this.copiedObject } 
        ));
        

    }
}

The really important thing to observe in the Javascript controller for child2 is the code in the handleClick function. I am using an object to pass both the number and name value in the CustomEvent.

On the surface this seems simple, but the official Salesforce documentation includes a warning that custom events should only pass primitive data, such as a string or a number and not an object. This is because any listener (which could be a malicious one) can mutate the passed object and change the values.

To avoid this issue, I am making a shallow copy of the eventObject into a new variable named copiedObject. Only the value of the copied object is passed in the detail of the CustomEvent.

If you found this post helpful, you might want to check out my Pluralsight course, “Communicate Between Salesforce Lightning Web Components”.

Building a Complex LWC app? You may need to learn more about how they communicate

Are you a Salesforce developer that has been tasked with building a complex app involving multiple Lightning Web Components (LWC’s)?

The most important thing to understand is all the ways these components can communicate. Without a solid understanding of this concept, you may struggle and inadvertently create a poor performing or error prone app.

That is why I am happy to announce that my latest Pluralsight course, “Communicate Between Salesforce Lightning Web Components” has just been released. This is not a course for beginners new to LWC’s or Salesforce. But, if you plan on building an app that involves multiple LWC’s and you already know the basics, then this course is for you.

Communicate Between Salesforce Lightning web Components

In this course you will learn how to effectively communicate between LWC’s. First you will discover the three methods used to communicate between components. Then you will learn details about each method by seeing how they work in a real-world app. By the end of the course, you will know how to build your own high-performing Lightning-based app that is assembled with Lightning Web Components. This course is focused solely on LWC communication.

I hope you find the course useful. If you do check it out and have feedback, I would love to hear it – good or bad. You can give feedback through Pluralsight or here on my blog. Either way, it would be appreciated. Thank you.

Farewell Package.xml…you will not be missed

Salesforce’s Spring 21 release has brought about a lot of big changes. Some I am not so thrilled with, but one has so far been nice to see.

Sandbox Source Tracking went GA with this release. This is meant to help us poor developers keep track of all metadata changes between our local VS Code source repositories and the actual Sandbox/Scratch orgs.

In a nutshell, it appears to me that the dreaded package.xml file will be going away, eventually. This file has caused far too many problems (especially for teams of developers). Instead of having to manually track all metadata data changes, Salesforce will automatically keep those changes synchronized between your local development workspace and the org. THANK YOU Salesforce!

Now before you get too excited, this is NOT going to be an easy transition. For starters, a force:source:pull will not get you all the metadata from an org. I experienced problems just trying to do a simple demo with a scratch org this past weekend, using brand new code.

I anticipate a lot of customers are going to experience huge problems as a result of this change. This will be especially difficult for legacy customers with huge monolith orgs that have not been untangled.

But, I do believe this step is necessary to allowing all Salesforce developers to really emerge from the 90’s and start doing serious modern web development. Before you go too far with this, you need to know what you are dealing with. Start by checking out this Developer Blog article. I am sure there will be lots more Trailhead modules/videos etc to come on this.

So, this is not some “magic pill” to solve all development/deployment problems. But, it is a good first step. Looking forward to seeing problems addressed and enhancements made.

Post 1 – Customizing your Salesforce Community with Code

This will be the first of a series of posts I will be doing about a new Pluralsight course titled, “Developing and Extending a Salesforce Community Experience with Code”.

Community Cloud (now known as Experience Cloud) has been part of the Salesforce platform for years and it is used by many companies to actively communicate with their communities of customers, partners and employees. Hence the community name.

Developing and Extending a Salesforce Community Experience with Code

Selecting a Template

The first step in creating a new community involves selecting a template. The template determines what type of community is created.

The important thing to realize is that there are two basic template types.

  • Lightning-based
  • Visualforce + tabs

To help you decide which type might be right for you, here is a comparison of the two.

Compare Community Template Types
Compare Community Template Types

I would suggest you select lightning-based templates unless there is some compelling reason to use a Visualforce template.

What you will learn in this course

In this course you will be learning about..

  • Developing custom Lightning components to extend a Lightning-based community
  • Building a Visualforce community with standard Visualforce pages and Apex classes.
  • What code-based sharing and visibility customizations you can make to secure your community.
  • Opportunities to extend your community through integrations with other communities and clouds

Stay tuned for additional posts that will cover the remaining modules for this course. You can access the course on Pluralsight here. If you do not have a subscription, then you can sign up for a free 10 day trial.

Need to learn all about Lightning Web Components (LWC’s)?

For anyone brand new to the Salesforce Lightning Web Component Framework, learning about all this can be quite challenging. Late last year I released a Pluralsight course named, “Salesforce Lighting Web Components: The Big Picture“.

This Big Picture course was designed to slow things down and give you a high-level overview of all the pieces that make up the framework. In a nutshell, Lightning Web Components can be used to build trusted and highly performant web apps that use Salesforce data to run anywhere.

In an effort to expose more developers to this powerful framework, I have put together the following promotional preview video that you can watch for free on this blog. I hope it helps give you a better and bigger picture of all that LWC’s have to offer.

Salesforce Lightning Web Components: The Big Picture

Top 5 Tips for Building Your First LWC

I am very honored to have been asked by 100daysoftrailhead.com to record a session about Top 5 Tips for Building Your 1st LWC. And with that, I wanted to write this post to summarize the tips that I featured in that presentation.

Tip # 1 – Hit the Trail

If you are brand new to Lightning Web Components, then you definitely want to begin by working through the Build Lightning Web Components trail on Trailhead. The trail several projects and modules and you do not have to work them all at once. But at the very least, you should complete the first one, Quick Start: Lighting Web Components.

Tip # 2 – Install the Salesforce Extended Expansion Pack

Better Option is to install the Salesforce Extended Expansion Pack
Better Option is to install the Salesforce Extended Expansion Pack

The official Salesforce docs tell you to install the Salesforce Extension Pack for Visual Studio Code. But, I suggest you also/or instead install the Salesforce Extended Expansion Pack, which you can do by Clicking the Extensions icon in the left toolbar of Visual Studio Code and then selecting Salesforce Extension Pack (Extended).

Select the Extended Expansion Pack though the Extensions icon in Visual Studio Code
Select the Extended Expansion Pack though the Extensions icon in Visual Studio Code

This extension pack will include 4 additional JavaScript libraries that you will more than likely need. They are XML, ESLint, Prettier and Apex PMD.

Tip # 3 – Embrace the Command Line Interface (CLI) Help

Don’t fear the CLI – Embrace it! I know that the Salesforce Extensions offers a very nifty Command Palette tool, but that does not cover everything that the CLI offers. By using the built-in help features, you not only get access to the latest docs (and that you can be rest assured of), but you can learn a lot about what the CLI Offers.

To access the help feature, just type the following sfdx help from a Terminal Window in Visual Studio Code. This will bring up results such as the following:

Access the CLI help feature from Terminal window
Access the CLI help feature from Terminal window

To drill down into one of the topics, such as the force one, use the following:

sfdx force --help

From there you can drill down as far as you need to, such as this command for accessing info about creating a Salesforce DX project:

sfdx force:project:create --help

Tip # 4 – Use Base Lightning Components Whenever Possible

The Base Lightning Components that Salesforce offers not only make your life as a developer so much easier, they are highly performant than anything you might try to create yourself. So, you should check them all out and make sure to use them whenever possible.

The Component library offers a handy Lightning Mini Playground that you can use to access sample HTML and JavaScript directly.

The Component Library offers a handy Lightning Mini Playground feature

Tip # 5 – Reference the Code in the Sample App Gallery

The Sample App Gallery includes real-world code that were all designed by the incredible developers with the Salesforce developer relations group. They not only demonstrate new Salesforce features, but best practices for how to create Lightning web components.

As you begin the process, the most important one to checkout is the LWC Recipes one. This GitHub repo features very short code snippets that demonstrate how to perform certain key operations.

Bonus Tip – Check out My New Pluralsight Course

This month, I also released my latest Pluralsight course, “Salesforce Lightning Web Components: The Big Picture“. You can find out more about it in this post. Once you have completed that course, you might want to checkout, “Building Your First Lightning Web Component (LWC) for Salesforce“.

New Pluralsight Course: Salesforce Lightning Web Components: The Big Picture

I am beyond happy to announce the release of my latest Pluralsight course, “Salesforce Lightning Web Components: The Big Picture“. This is a high-level overview of all the important things that make up this new modern and standards-based framework.

Viewers will first explore what makes up the entire Lightning Web Stack. This will include discovering the open-source Lightning Design System, which is key to the entire Lightning Experience.

Lightning Web Stack
Lightning Web Stack

Learners will also learn about the modern developer tools that Salesforce now offers. These tools offer developers a way to build robust and high-performing web apps. The tools should be instantly familiar to developers familiar with building modern web apps using frameworks like React or Vue.

Visual Studio Code and the Salesforce Extension Pack
Visual Studio Code and the Salesforce Extension Pack

When learners are finished, they should have the skills and knowledge of Lightning Web Components needed to build an adoption plan for their own Salesforce organizations.

And if you watch the course, please feel free to give me feedback. Good or bad. Thanks!

EDIT: Go here to access a promotional video I created for this course. It is a condensed 10 minute preview of the course that should give you a good idea of what it offers.

Salesforce Trailhead: Approach with Caution

Proceed to the Salesforce Trailhead with caution

As a former member of the Trailhead team, I am hesitant to write this, but I think it is an important thing for people to be aware of. If you have been using Trailhead for longer than a year, then you need to be aware of these pretty serious limitations.

While you can retake challenges for badges and projects, you cannot do so for Superbadges. More importantly, once you complete a badge, you have no way of knowing that the content for that badge may have been significantly updated. As in, all the content you understood when you completed the badge, is no longer relevant.

As I am sure you are aware, Salesforce does major releases three times a year. When they do, they prepare comprehensive release notes and the Trailhead authors are instructed to review these notes and update their content as necessary. That part is great. What is not great is that you as a consumer of Trailhead content have no way of knowing that the content was updated (without revisiting EVERY badge you have earned to examine the content).

The badge itself just indicates that it was completed on a certain date. As in the image below of a badge I completed in 2015. This badge has since been significantly updated and the content that was once relevant when I completed the badge is VERY different.

Trailhead badge completed in 2015 that now has VERY different content

How do you know that you are aware of the latest features and updates to the platform? Well, it is up to you to pick through the release notes and then cross reference any Trailhead content that you may have completed. Nice, right?

Just wanted to make sure everyone was aware of this (what I consider to be) serious limitation. I hope the team is actively addressing it. I would say I know, but they don’t talk to me since I left the team.