Day: December 28, 2018

Platform Events Subscribe using Lightning Component

Platform events are part of Salesforce’s enterprise messaging platform. The platform provides an event-driven messaging architecture to enable apps to communicate inside and outside of Salesforce. Here let us discuss how to subscribe to the platform events in the lightning component using lightning: empApi. The lightning:empApi component provides access to methods for subscribing to a streaming channel and listening to event messages. All streaming channels are supported, including channels for platform events, PushTopic events, generic events, and Change Data Capture events. The lightning:empApi component uses a shared CometD connection.we will be subscribing the platform event object as shown below.
Here is the simple lightning component that will subscribe to the platform events and listen for notifications.


 

once a platform event is published, you can able to the response from the subscribed lightning component as shown below

Publishing Platform Events

The Salesforce enterprise messaging platform offers the benefits of event-driven software architectures. Platform events are the event messages (or notifications) that your apps send and receive to take further action. Platform events simplify the process of communicating changes and responding to them without writing complex logic. Publishers and subscribers communicate with each other through events. One or more subscribers can listen to the same event and carry out actions. Here we will see how many ways you can able to publish the platform events in Salesforce. After a platform event has been defined in your Salesforce org, publish event messages from a Salesforce app using processes, flows, or Apex or an external app using Salesforce APIs.Here is the simple platform event object we will be using in the examples here

Here are the different ways you can able to publish the platform events in Salesforce

Option 1: Using Process Builder  

You can able to publish the platform events using process builder. To publish event messages, add a Create a Record action to the appropriate process. Where you’d usually pick an object to create, select the platform event. Here is the simple process builder that will publish the platform event when an order is created

This process builder will publish the platform event whenever the order record is created.

Option 2: Using flow 

Another great usage of the flow is you can able to publish the platform events using the flows. Use flows to publish event messages from a Salesforce app as part of some user interaction, an automated process, Apex, or workflow action. To publish event messages, add a Record Create or a Fast Create element to the appropriate flow. Where you’d usually pick an object to create, select the platform event. Here is the simple flow that we will be using it create a platform event on click on the button from the order record. Here is the Fast lookup screen that will fetch the order from the database.

Here is the record create screen that will be inserting the data into the platform event.

Final Flow looks like below

Now create a quick action from the flow and add it to the order page layout. once you click on the quick action then it will publish into the platform events.

Option 3: Using Apex

You can able to publish the platform event using apex. To publish event messages, call the EventBus.publish method. Here is the sample apex trigger that will create platform events.

Option 4: Using External Apps 

You can able to publish the platform events by using third-party apps with API support. For example, you can able to publish the platform events using SoapUI. Please refer to this link 

Option 5: Using Salesforce APIs

External apps use an API to publish platform event messages. Publish events by creating records of your event in the same way that you insert sObjects. You can use any Salesforce API to create platform events, such as SOAP API, REST API, or Bulk API. When publishing an event message, the result that the API returns contains information about whether the operation was successful and the errors encountered. If the success field is true, the event was published for a standard-volume event. For a high-volume event, the publish request is queued in Salesforce and the event message might not be published immediately. If the success field
is false, the event publish operation resulted in errors, which are returned in the errors field. The returned result also contains the Id system field. The Id field value is not included in the event message delivered to subscribers. It is not used to identify an event message, and is not always unique. Subscribers can use the ReplayId system field, which is included in the delivered message, to identify the position of the event in the stream. To publish a platform event message using REST API, send a POST request to the following endpoint.

You can able to send the post request as shown below from workbench as shown below.

 

 

Render Lists In Lightning Web Components

One of the most common use cases is to iterate through the collection when you are working on data collection. Let’s discuss here what all the different ways to do it in lightning web components. To render a list of items, use for each directive or the iterator directive to iterate over an array. Add the directive to a nested <template> tag that encloses the HTML elements you want to repeat. Please refer this link for web component environment setup

Using for:each directive

Let us discuss here how to use the for:each. When using the for:each directive, use for:item=”currentItem” to access the current item. To assign a key to the first element in the nested template, use the key={uniqueId} directive. Regardless of which directive you use, you must use a key directive to assign a unique ID to each item. When a list changes, the framework uses the key to rerender only the item that changed. The key must be a string or a number, it can’t be an object. You can’t use the index as a value for the key. Assign unique keys to an incoming data set. Here is the simple apex class that will get the data from the account object and its contacts. create an apex class using the below  SFDX command.

Here is the complete code.

Below is the lightning web component that will iterate over an array called accounts, which is defined in the component’s JavaScript class.  Run the following SFDX command to create a web component

CollectionExample.html

the above markup is iterating the data using the for:each directive as like below.

CollectionExample.js

CollectionExample.js-meta.xml

Now push the component changes to scratch org and add this component to the record page. You can able to see the collection iteration data as shown below.

 

Nested Iteration using for:each directive

Now let us iterate the nested loop using the for:each directive .here is the example that will render the account and its contacts. Update the CollectionExample.html markup with the below code and push the changes to scratch org.

Push the change to scratch org and reload the page. Here is the final output.

 

Using Iterator directive

Iterator directive is another way to render the collection data. To apply a special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use iteratorName to access these properties:

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

This sample code uses the same array as the previous example. To apply special rendering to the first and last items in the list, the code uses the first and last properties with the if:true directive. Update the  CollectionExample.html code with below code . in this example we will be displaying the list of accounts.

CollectionExample.css 

Push the changes to scratch org and you can able to see these changes after reload.

Now let us see how to do the nested iteration using iterator directives . in this example we will be displaying accounts and its contacts. here is the HTML markup for the nested iteration.

 

Push the changes to the scratch org and reload the page. you can able to see the output as shown below and will be displayed account and its contacts.

Call Apex Methods In Lightning web components

Let’s discuss here how to call the apex class from the Lightning web components. Lightning web components can import methods from Apex classes into the JavaScript classes using ES6 import. 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. 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. 

Refer this link for how to configure the Salesforce dx for web components 

Import Syntax 

You can able use default export syntax to import an Apex method via the @salesforce/apex scoped module into JavaScript controller class. The Syntax looks like below.

apexMethod—The imported symbol that identifies the Apex method.
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.
Classname—The name of the Apex class.

Create Apex Class 

In this example, we will be getting account data and show it into the UI. Create an apex class using SFDX create apex class command.

Here is the apex class. To expose an Apex method to a Lightning web component, the method must be static and either global or public. Annotate the method with @AuraEnabled

Now you can able to call the apex class in  Lightning web component using these different ways.

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

Wire an Apex Method to a Property

If an Apex method is annotated with @AuraEnabled(Cacheable=true), you can invoke it from a component via the wire service. You can @wire a property or a function. Here is the syntax

Create a Lightning web component using below SFDX commands

Here is the LWCWireEx.html markup for the lightning web components.

Here is the LWCWireEx.js class

Here is the LWCWireEx.js-meta.xml markup.

Push the changes to scratch org and add the lightning web component to the record page. You can able to see the result like below.

Wire an Apex Method to a Function

Now let’s look at how to wire an apex method to function.we will be updating the same code here to operate the apex method as function.

Update the LWCWireEx.js class as shown below

update the LWCWireEx.html markup as shown below

Push the changes to scratch org and add the lightning web component to the record page. You can able to see the result like below.

 

Call an Apex Method Imperatively

Now let’s see here how to call apex method imperatively. Create a new Lightning web component using the below SFDX command

Use the below ImperativEx.html code

Use the below ImperativEx.js class code

Use the below ImperativEx.js-meta.xml class code

push the changes to scratch org and add the lightning web component to the record page and you can able to see the below result when you click on the button .

Lightning Web Components Example

Let’s discuss the Salesforce Lightning Web Components with hello world example which is the perfect start to understand how the Lightning Web Components worksWeb components are a set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. Custom components and widgets build on the Web Component standards, will work across modern browsers, and can be used with any JavaScript library or framework that works with HTML.Web components are based on existing web standards. Features to support web components are currently being added to the HTML and DOM specs, letting web developers easily extend HTML with new elements with encapsulated styling and custom behavior. Lightning Web Components is a new programming model for building Lightning components. It leverages web standards breakthroughs, can coexist and interoperate with the Aura programming model and delivers unparalleled performance. To create and develop Lightning Web Components and leverage their powerful features and performance benefits, you need to set up Salesforce DX.

Environment setup

  1. Sign up for spring 19 pre-release org from here.
  2. Enable Dev Hub
  3. Install SFDX CLI spring 19 version. Please check the SFDX version to be matched to 45.0.X on CLI
  4. Download and install the latest version of Visual Studio Code  if not available
  5. Install visual studio code Salesforce Extension Pack extension 
  6. Install Lightning Web Components extension for visual studio code

Time to Code “Hello World” Component 

Now your development setup is complete and you can able to start coding the helloworld web component and let us get the start.

  1. Open Visual Studio Code and run the SFDX  commands from the visual studio code command palette.To open command palette press Command + Shift + P on a Mac or Ctrl + Shift + P on Windows.
  2. Run SFDX: Create Project command to create a project from Command Palette and Enter helloworld as the project name.

            3. Authorize a Dev Hub by using SFDX: Authorize a Dev Hub command from the command Palette and Log in using your pre-release Dev Hub org credentials. Click Allow.

        4. Create a Scratch Org by using SFDX: Create a Default Scratch Org command from the command palette. Press Enter to accept the default project-scratch-def.json. Press Enter to accept helloworld scratch org alias.
           5. Now Create a Lightning Web Component using SFDX: Create Lightning Web Component. Press Enter to accept the default to force-app/main/default/lwc folder. Type helloworld for the name of the new component. Press Enter. You can able to see the newly created component under force-app/main/default/lwc folder. 

Now in the helloworld.html file copy and paste the below code.

In the above HTML markups, you can able to template based binding syntax {greeting}  that is used to bind the properties from the controller.

In the helloworld.js JavaScript file, copy and paste the following code.

@track is used to track the property’s value and re-render a component when it changes.

In the XML file helloWorld.js-meta.xml, copy and paste the following code which will indicate where in the app builder this lightning component is available.

Push to a Scratch Org

Now push your changes from the local dev env to Salesforce scratch org.  Run the following command from the visual code command palette SFDX: Push Source to Default Scratch Org.

Add Component to App in Lightning Experience

  1. Select SFDX: Open Default Org command from the command palette to open the scratch org 
  2. Add the helloworld Lightning web component form to the contact record page and save changes.

That’s it. Now you have successfully created your first lightning web component. But just let us make some more changes to a lightning web component. Let’s call the simple hello world message from the server side apex class

Create Apex Class 

Now create an apex in SFDX env . To create an apex class from the SFDX run the this SFDX :Create Apex Class command from command palette. 

Here is the simple apex class “HelloWorld”

Change your helloworld.html code as shown below

Change your helloworld.js code as shown below

In the above code, you have to import the apex class in the JavaScript controller and use the @wire property to bind the apex method.

Now push the changes from local development to scratch org .to push the changes from the SFDX local to scratch org run the SFDX: Push Source to Default Scratch Org command from the command platter.

Now refresh the record page and you can able to see hello world message from the apex class as shown below.