Showing posts with label lightning. Show all posts
Showing posts with label lightning. Show all posts

Using Lightning Message Service to communicate between lightning components and visualforce

Lightning message service allows you to communicate between all UI technologies of Salesforce (LWC, Aura and Visualforce). This is the recommended way to communicate between lightning components and Visualforce.

Lighting message service communication works in below three steps

  1. Create a new MessageChannel metadata file and deploy to your org
  2. Publish a message from one of the three UI technologies
  3. Subscribe to the message in any of the three UI technologies

1) Creating new MessageChannel

Currently Salesforce do not provide any option in the UI to create MessageChannel. So you have to deploy it as metadata. isExposed setting in metadata allow you to enable communicate between different namespaces/managed packages.

Copy below code metadata to messageChannels folder in your code folder. Name the file as CarSelectionChannel.messageChannel-meta.xml


If you have sfdx installed, you can use below line to deploy the file.

sfdx force:source:deploy -p "pathToFile" -u targetOrgAliasHere

2) Publish event on the MessageChannel

This step varies depending on the whether you are publishing it from LWC or Aura or Visualforce. Our example scenario outlines subscribing and publishing from all three technologies.

3) Subscribing to events on MessageChannel

This step also varies depending on the whether you are publishing it from LWC or Aura or Visualforce. Our example scenario outlines subscribing and listening from all three technologies.

Visualforce Example

Here we use sforce.one methods. This do not work as a stand alone visualforce page. Make sure you are inside lightning experience. ie create a visualforce page with below code, create a tab for that visualforce page and check from lightning experience.

Aura Example

Here we use lightning:messageChannel in the component to subscribe to event.

LWC Example

Here we import @salesforce/messageChannel/CarSelectionChannel__c in JavaScript controller. Also we use subscribe, unsubscribe methods imported from lightning/messageService to subscribe to event.

Please note that if you are just publishing message to channel and not listening to it, you just need to import publish method and the channel. Then you can use the code in handleCarSelect method to publish message to the channel.

Create app builder page to see the result in one page

In order to confirm that the event is getting published and received in all three technologies, put above visualforce, aura and lwc components in a new App builder page and add the page to any app. It should looks like the screenshot at starting of this post.

All ways to communicate between lightning components (Aura and LWC)

There are a lot of different ways to communicate between different types of lightning components (lwc to lwc, lwc to aura, aura to lwc etc). In this blog we will cover all different ways of communicating between different types of lwc and aura components.

Communication patterns between Lightning components


Interactions with Visualforce Page

Still some features like PDF rendering are only supported in Visualforce. There is a chance you might need to interact between lightning components and visualforce components. Some examples are listed below,

  • Embedding visualforce page inside aura [COMING SOON]
  • Embedding aura app inside visualforce [COMING SOON]
  • Embedding visualforce page inside lwc [COMING SOON]
  • Embedding lwc inside visualforce page [COMING SOON]

Communication between independent lightning web component and Aura component - aurapubsub

You can use pubsub library or lightning message service to communicate between components that are not in same DOM hierarchy. These methods can be used to communicate between sibling components in an outer lwc component or between to lwc components that are dropped separately in lightning app builder.

Here we will go through an example of lwcComponentA that displays three car company names using radio button. When a car company is selected in the child component we will fire a carselected event from child component with the name selected by the user. Parent component will listen to this event and display the selected name in parent component. Parent component auraComponentB, will listen to this event and display the selected name in auraComponentB.

Example

1) Create a utility lwc component with name pubsub. Copy paste below code into it's JavaScript file. Please note that this is a utility component provided by Salesforce. But current version available in the link is doing pageRef check and it is not working as expected. So use below version shared by another Salesforce team member instead.


2) Create a utility lwc component with name auraPubSub Copy paste below code into it's JavaScript file.Please note that this is a utility component provided by Salesforce.


3) Create a lwc component with name lwcComponentA


4) Create a aura component with name auraComponentB


5) Create a aura test app lwcToAuraSiblingTest in which lwcToAuraSiblingTest.App can contain both components

6) Now if you open the aura app, it will look like

child to parent lwc communication

Explanation

In lwcComponentA component, when value of car is changed in the radio button, it calls JavaScript method in controller sendDataToComponentB. This function uses fireEvent method in pubsub library and fires a custom event with name carselected. Selected carname is also passed as data in the event payload.

auraComponentB component, has a listener added for carselected event. It is achieved by using registerListener method in auraPubsub utility. Inside handlePubsubReady methos we add a listener using the line registerListener('carselected', callback);. This basically tells "whenever a carselected event is received, go to callback inside handlePubsubReady method in JavaScript controller.

Finally when diplaySelectedCar method is called, we take value from the event payload and assigns to valueGotFromA variable in JavaScript

Things to Note

  • This is a common pattern to pass values between independent aura and lwc components in same page.
  • Make sure that you are using the pubsub and auraPubsub libraries shared above. Otherwise you might get an error pubsub listeners need a "@wire(CurrentPageReference) pageRef" property.

Communication between independent lightning web components - pubsub

You can use pubsub library or lightning message service to communicate between components that are not in same DOM hierarchy. These methods can be used to communicate between sibling components in an outer lwc component or between to lwc components that are dropped separately in lightning app builder.

Here we will go through an example of lwcComponentA that displays three car company names using radio button. When a car company is selected in this component we will fire a carselected event from lwcComponentA with the name selected by the user. A separate lwcComponentB, that is outside direct DOM hierarchy of lwcComponentA, will listen to this event and display the selected name in lwcComponentB.

Example

1) Create a utility lwc component with name pubsub. Copy paste below code into it's JavaScript file. Please note that this is a utility component provided by Salesforce. But current version available in the link is doing pageRef check and it is not working as expected. So use below version shared by another Salesforce team member instead.


2) Create a lwc component with name lwcComponentA


3) Create a lwc component with name lwcComponentB


3) Create a parent lwc component with name parentLwc that can contain both components

3) Now if you surface the parent component in lightning experience, it will look like

child to parent lwc communication

Explanation

In lwcComponentA component, when value of car is changed in the radio button, it calls JavaScript method in controller sendDataTolwcComponentB. This function uses fireEvent method in pubsub library and fires a custom event with name carselected. Selected carname is also passed as data in the event payload.

lwcComponentB component, has a listener added for carselected event. It is achieved by using registerListener method in pubsub utility. Inside connected callback we add a listener using the line registerListener('carselected', this.diplaySelectedCar, this);. This basically tells "whenever a carselected event is received, call diplaySelectedCar method in JavaScript controller.

Finally when diplaySelectedCar method is called, we take value from the event payload and assigns to valueGotFromA variable in JavaScript

Things to Note

  • This is a common pattern to pass values between independent lwc components in same page.
  • Make sure that you are using the pubsub library shared above. Otherwise you might get an error pubsub listeners need a "@wire(CurrentPageReference) pageRef" property.

Communicating from child lightning web component to parent lightning web component

You need to fire CustomEvent from child component to communicate to a parent component.

Here we will go through an example of a child component that displays three car company names as a radio button. When a car company is selected in the child component we will fire a carchange event from child component with the name selected by the user. Parent component will listen to this event and display the selected name in parent component.

Example

1) Create an lwc component with name childLwc


2) Create an lwc component with name parentLwc

3) Now if you surface the parent component in lightning experience, it will look like

child to parent lwc communication

Explanation

In childLwc component, when value of car is changed in the radio button, it calls JavaScript method in controller sendDataToParent. This function then dispatches/fires a custom event with name carchange. For every custom event, if you are passing data, you need to pass it as a JSON object with detail attribute.

parentLwc component, has a listener added for carchange event. It is achieved by adding on+eventname attribute while refering child component in html. In our case it is oncarchange attribute added at line 5 of parentLwc component html. This basically tells "whenever a carchage event is received, call displayValueInParent method in JavaScript controller.

Finally when displayValueInParent method is called, we take value from the event.details and assigns to valueSentByChild variable in JavaScript

Things to Note

  • This is a very common pattern to pass values from child component to parent component
  • Make sure that you are using detail attribute while sending data
  • Make sure that your event name is all small letters. ie carchange instead of carChange
  • Make sure that your listener name is all small letters. ie oncarchange instead of oncarChange

Communicating from parent lightning web component to child lightning web component

It is easy to communicate/send data from a parent lightning web component to a child lwc component. You can define a variable in the child lwc component javascript file, annotated it with @api annotation and finally pass value from parent component to the child component by using this variable name.

Example

1) Create an lwc component with name childLWCComponent


2) Create an lwc component with name parentLWCComponent

If you surface the parent component in lightning experience, it will looks like

parent to child lwc communication

Explanation

Here childLWCComponent has a javascript variable childVariable annotated with @api annotation. Parent component can pass value using this attribute name. But please note that camel case variable names in child component is converted to kebab case in parent component.

Use Cases

This is the most common form of communication/exchange of data between lwc components. Usually complex lightning apps are built as a combination of multiple child lwc components. ie a parent lwc component contining multiple child lwc components. This parent component will retain data that is needed by all child components and sends it to child components using variables defined in child component using @api annotation.


How to display a modal popup using aura components

When you build custom interfaces it is very common need to show a modal window or a popup window. In this example we will go through how we can build a reusable modal window using lightning aura components. If you are looking for a lightning web component (lwc) version of modal/popup component please check out lwc modal.

Use cases

  • Display modal window or popup window in user interface
  • Show Yes/No confirmation modal popups

Steps to Implement

STEP 1 :- Create a component event with name Util_PressEvent. This event is used to track click event on buttons that can be used to add listeners on modal component. Find the event file and metadata below,

STEP 2 :- Create an aura component with name Util_ModalWindow. This component will contain all code needed to show and hide the modal popup,

STEP 3 :- You are all set to use the modal component. Let us use the modal component inside an aura component to show a modal popup. Here we are using a parent aura component with name DemoAuraComponent to show modal popup.


Explanation

Here we can add any content including other aura components between opening and closing tags of Util_ModalWindow. All the content between the tags will be rendered as the body of the modal window.

Example

  • Before opening Modal

  • After opening modal


How to use lightning data service in lightning web components(LWC)

Lightning data service allows you to cache and share data between lightning components using browser cache. Lightning framework takes care of managing cached data in browser. You do not need to write any code to interact with browser cache. There is no need to write any apex code also. Since the data is coming from client/browser cache, you can access data quickly if it is cached already. Lightning data service is built on top of Salesforce user interface API.

Use cases

  • Create simple forms that can create/view/edit single record.
  • lightning-record-form can be used to display data from all fields in standard page layout.
  • If you are building a component to use in a record details page and the component only updates the fields in the same record, it is highly recommended to use lightning data service, since Salesforce keeps data in sync with details page automatically.


Explanation

You can use "getRecord" and "updateRecord" methods from "lightning/uiRecordApi" to get record and update record from lightning data service respectively. After getting a record you need to wire it to a variable to make it available in UI. Then you need to use "getFieldValue" method and create a getter method to make the field available in the UI.

If we go step by step in the flow, below actions happen in a sequence when the component is loaded and value is changed.

  1. Component gets loaded in a record details page and salesforce passes "recordId" attribute is passed in to the component
  2. @wire annotation uses "getRecord" to get data from Salesforce server using lightning data service
  3. This data is made available to HTML through "checkboxValue" getter method. At this point if the data in contact record is checked, it will be dispalyed in UI
  4. Say user changed the value of checkbox by clicking it. "handleFieldChange" method is called. This method creates an object to update and passes to "updateContact" method
  5. "updateContact" method uses "updateRecord" method from lightning data service to send this data to Salesforce server and update
  6. Based on success or failure, a toast message is shown by firing an eveng


How to use

  • This code assumes that you have a checkbox field in your contact object with API name "My_Checkbox_Field__c"
  • Create an LWC component with name "lwcDataserviceComponent". Copy HTML, JS and XML code above to relevant files
  • Once the component is saved, you should be able to see it in app builder interface for contact object. This is because we have made it available through the metadata file of lightning component
  • Drag and drop the component to contact page and activate it
  • If you have the same field in record details section, you will be able to see that getting updated in real time as you update the checkbox in the lwc component.

How to use a lightning web components(LWC) inside an aura component

It is very easy to embed lightning web components(lwc) inside aura components. But remember that you cannot insert an aura component inside an LWC component.

Use cases

  • You can use this approach to migrate/modernize your big aura applications to LWC step by step. Suppose there is a big aura application that has four big aura sub components. We can migrate the application to LWC framework, by migrating one of these four aura components to LWC at a time.


Explanation

Here we are creating an LWC component with name "childLWCComponent". We display data from a javascript variable in controller with name "testVariable" in the UI. To embed we are using an aura application with name TestApp. In order to embed "childLWCComponent" LWC component in aura app, you can just use the syntax "<c:childLWCComponent></c:childLWCComponent>"


How to use

  • Create an LWC component with name childLWCComponent
  • Copy content from above code to childLWCComponent component. childLWCComponent.html is the HTML file and childLWCComponent.js is the Javascript file
  • Create an aura app with name "Testapp.app"
  • Copy content from above code sample to Testapp.app file
  • Navigate to "yourOrgBaseUrl/c/TestApp.app" to see the result