When Salesforce is life!

Tag: LWC

[Salesforce / LWC] Autocomplete magic with HTML Datalist

Ivano Guerini is a Salesforce Senior Developer at Webresults (Engineering Group) since 2015.
He started my career on Salesforce during his university studies and based his final thesis on it.
He’s passionate about technology and development, in his spare time he enjoys developing applications mainly on Node.js.


The <datalist> element is a new tag available in the HTML5.
This element can be used to create native autocomplete dropdowns without using complex JS and DOM manipulation for data filtering.

As you may have experienced, autocomplete picklist is a usefull component commonly used in forms to facilitate users in finding the correct value in case of very large lists of values.

In this article post, you’re going to learn how to use the datalist element to create a autocomplete dropdowns as Lightning Web Component.

For the TL;DR guys over there, this is the repo.

Let’s get started.

First let’s see how it works in an HTML page.

Simply write this code in an HTML page and we obtain a autocomplete dropdown like the below.

<input list="countries">

<datalist id="countries">
	<option>Italy</option>
	<option>Spain</option>
	<option>France</option>
	<option>USA</option>
	<option>England</option>
	<option>Belgium</option>
	<option>Brazil</option>
	<option>Mauritius</option>
	<option>Colombia</option>
	<option>Portugal</option>
	<option>Russia</option>
	<option>Mauritania</option>
</datalist>

Simple like that, all without any JS code.

Now let’s try to do the same in Salesforce.
Open your favorite IDE, and create a new LWC component, naming it ‘autocomplete’.

The html template we report the same code written above.

<template>
    <input id="input" name="input" list="countries" class="slds-input" type="text" />
    <datalist id="countries">
		<option>Italy</option>
		<option>Spain</option>
		<option>France</option>
		<option>USA</option>
		<option>England</option>
		<option>Belgium</option>
		<option>Brazil</option>
		<option>Mauritius</option>
		<option>Colombia</option>
		<option>Portugal</option>
		<option>Russia</option>
		<option>Mauritania</option>
	</datalist>
</template>

If we try to execute this component, we will see that it does not work as we would expect.
This is because the link between the input and the datalit is managed through the Id attribute. But as Salesforce reminds us:

The IDs that you define in HTML templates may be transformed into globally unique values when the template is rendered. If you use an ID selector in JavaScript, it won’t match the transformed ID.

To overcome this problem we can take advantage of a few lines of JS code, hooking up to the rerenderCallback.
Then in the Javascript controller we write the following function:

renderedCallback() {
     let listId = this.template.querySelector('datalist').id;
     this.template.querySelector("input").setAttribute("list", listId);
}

This code simply searches for our Datalist element and retrieves the ID generated by Salesforce, and consequently updates the input list attribute with the new Value.

Again the rendered callback can run a lot of times, but our code must be executed only once. To do it we can use a private attribute to know if the renderedCallback has been already executed:

initialized = false;

renderedCallback() {
        if (this.initialized) {
            return;
        }
        this.initialized = true;
        let listId = this.template.querySelector('datalist').id;
        this.template.querySelector("input").setAttribute("list", listId);
    }

Now our LWC component will work as autocomplete dropdown.

Let’s evolve it a bit, using dinamic options and decorating it with a label ad other attributes.

The HTML template will tranform like this:

<template>
    <label class="slds-form-element__label" for="input">
        <template if:true={required}>
            <abbr class="slds-required" title="required">* </abbr>
        </template>
        {label}
    </label>
    <div class="slds-form-element__control">
        <input id="input" name="input" list="valueList" placeholder={placeholder} required={required} class="slds-input" type="text"  />
        <datalist id="valueList" class="">
            <template for:each={values} for:item='item'>
                <option key={item.key} value={item.value}>{item.value}</option>
            </template>
        </datalist>
    </div>
</template>

In the JS controller we handle this values with @api decorator.

import { LightningElement, api } from 'lwc';

export default class Autocomplete extends LightningElement {
    @api values;
    @api label = '';
    @api name = '';
    @api required;
    @api placeholder = '';
    initialized = false;

    renderedCallback() {
        if (this.initialized) {
            return;
        }
        this.initialized = true;
        let listId = this.template.querySelector('datalist').id;
        this.template.querySelector("input").setAttribute("list", listId);
    }

}

Full repo here.

[Salesforce / Lightning Web Components] Build Lightning fast Salesforce Apps

Let’s talk about a great new addition of the Spring’19 platform release to the
Salesforce Dev world, the Lightning Web Components framework, with our guest blogger Priscilla Sharon, Salesforce Business Solution Executive for DemandBlue.

DemandBlue is in the business of helping its customers maximize their Salesforce investment through predictable outcomes. As we thrive in an era of cloud-based Infrastructure, Platform and Software services, DemandBlue has pioneered “Service-as-a-Service” through a value-based On Demand Service model that drives bottom-line results. They foster innovation through “Continuous Engagement and On Demand Execution” that offers their customers Speed, Value and Success to achieve their current and future business objectives.


Salesforce launched Lightning Web Components as part of Spring ’19 pre-release to enable a quicker and easier way to program applications on the Salesforce Lightning platform. It engages modern Javascript innovations such as web components, custom elements, shadow DOM and more. Lightning Web Components is the Salesforce implementation of Lightweight frameworks built as per the web standards. It provides specialized salesforce services in addition to the core stack, such as Base Lightning Components, Lightning Data Service, User Interface API, etc.

Read on to discover how the Lightning Web Components fuses Web components programming model with Salesforce metadata and services to deliver unparalleled performance and productivity.

With Lightning Web Components, we are giving developers a standards-driven JavaScript model for building enterprise apps on Lightning. Every time we release a new platform capability we see an acceleration of innovation in our 150,000 customer base, and we are excited to see what our community of developers will do with Lightning Web Components.

Mike Rosenbaum, EVP of Product, Salesforce

Why Lightning Web Components

Lightning Web Components is like a newer version of Lightning Components with additional features.

  • Knowledge Domain – Developers who know Web Components are familiar with Salesforce Lightning Web Components out-of-the-box. Aura is proprietary, so the better you know the web standards, the better you’ll have of skills that can be used outside Salesforce.
  • Better Execution – Lightning Web Components leverages built-in browser security features from Web Components standards, which reduces the level of custom coding, which means they run faster and are more consistent in how they ensure security. Moreover, events have a limited scope, so there is lesser processing required handling events.
  • New Security Features – It gives better CSS isolation, DOM isolation, script isolation and limited event scope that facilitate a more consistent component design.
  • ES6+ – We have a better support for ES6 and ES7 that is not available in Aura. This enables you to do more with less coding. This also transpires code to work in IE 11 and other browsers which were not supported earlier.
  • More Consistent Data Binding – The not so user-friendly two-way data binding has been eliminated. This pushes developers to coordinate the way in which data moves between components. It also means that data binding will work as expected, without any unforeseen problems from Aura.
  • Mixins – You can even import accessible methods from other components and import specific Apex methods from multiple classes. Moreover, the Apex methods can be cached for improved performance.

What Lightning Web Components means for Developers and Customers

Cutting-Edge Advantages of Lightning Web Components

Boosted Performance – Developing Lightning Web Components does not involve complex abstractions to run on the browser, providing better performance to end users.

Ease of Use – Post development, the admins can deploy Lightning Web components with just clicks, not code to the applications.

Standardized – Salesforce Lightning Web Components is built on ES6+ that provides developers with modern and advanced JavaScript features.

How to create a Lightning Web Components framework?

LWC (Lightning Web Components) cannot be created directly from the developer console. You need to set up Salesforce DX to create a Lightning component. After the SFDX setup, you need to do a few more things:

  • Sign-up for development org
  • Get your Salesforce DX plugin updated with the latest release (Spring’19). Run the command below in your terminal or command prompt.
  • Command:
sfdx update  
  • Once you finish this process, follow the trailhead link to set up the basic project and create a basic Lightning Web Component

Transition from Aura Components to Lightning Web Components

Developers using Aura framework to build lightning components can continue to work on it as the Aura components will continue to function like before. However, the new components can be created using Aura or the Lightning Web Component framework. For future developments, it is best if you use the Lightning Web Components.

Lightning Web Components Availability

Lightning Web Components are available for users since February 2019 in Enterprise, Unlimited, Performance and Developer editions.

For more information, check out the official Salesforce page on Lightning Web Components.

Powered by WordPress & Theme by Anders Norén