Component That Speaks To You | Lightning Component | Salesforce

 

Component That Speaks To You

Hello Kid!! I hope you are doing great. Thank you for taking some time to learn something new really appreciated.

In this episode, we will learn how we can let our component development more interactive with the end-user.

Before we start :
Before starting, let's understand how your lightning component can play a sound without any static resource. Yess!! that's correct we are not going to use any static resource or recorded sound.

In this episode, we will use Web Speech Synthesis API which is directly available in your browser. Where you just need to pass the string/text and your browser will read that text for you.

While using salesforce lightning component we can use this but as you are well aware that salesforce is using LockerService to block some of the browser features for security purpose. 

Now, how we can use it then? 
To use Speech Synthesis Web API we need to use component API version below 40 as LockerService introduced in API version 40. This is for salesforce AURA Component.

Can we use it in LWC ?
Directly you cannot use it as LWC will work on a component version 45+. But there is a workaround which we can use to use this API in LWC as well. I will share that in the upcoming episodes.

What's the recipe for today ?
In this episode, We will create a lightning component to renew the Insurance if the Insurance is expired. Hence whenever you open the insurance record your component will speak if its Live 


or Expired




If it's Expired it will tell you that 'it's expired please renew the insurance now' and then once you select the next expiry date it will give you the confirmation of renewal of Insurance as well as the updated status of insurance.

Let's get started.....

Pre-requisites :

Please create the Object and Fields as below :

Object
Label : Insurance (Insurance__c)

Fields :

1 ->
Label : Start Date (Start_Date__c)
Data Type : Date

2 -> 
Label : End Date (End_Date__c)
Data Type : Date

3 -> 
Label : isExpired(isExpired__c)
Data Type : Formula (Checkbox)
Formula : IF(End_Date__c < TODAY() , true, false)

isExpired is the field which will decide whether the insurance is expired or not.

Now let's get started........

Now open your developer console and create a lightning component as "renewInsurance"

Let's create it as 

renewInsurance.cmp
---------------------------------------
<aura:component controller ="insuranceController"  implements="flexipage:availableForAllPageTypes,force:hasRecordId" access="global">
<!-- attributes defined below -->
 <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
 <aura:attribute name="recordId" type="String"/>
 <aura:attribute name="renewDate" type="Date"/>
 <aura:attribute name="showDetail" type="Boolean" default="false"/>
 <aura:attribute name="record" type="Insurance__c" />
    
<!-- LDS to get current record data using below -->
 <force:recordData layoutType="FULL"
                   recordId="{!v.recordId}"
                   targetFields="{!v.record}"
                   recordUpdated="{!c.doInit}"/>

<!-- below code to display expired based on isExpired checkbox-->
<lightning:card >
  <aura:if isTrue="{!v.showDetail}">
  <h1 style="color:#ec524b" class="status">EXPIRED</h1>
  <h1 class="renewlabel">Renew Insurance now</h1>
  <p style="margin:5px"> 
  <lightning:input type="date" 
                    name="Next Expiry Date" 
                    label="Next Expiry Date"  
                    value="{!v.renewDate}"                        
                    style="padding-bottom:5px"/> 
<lightning:button variant="brand" label="Update" title="Brand action" onclick="{!c.handleChange}"/>
   </p>

<!--below code to display live based on isExpired checkbox-->
  <aura:set attribute="else">
     <h1 style="color:#01c5c4" class="status">LIVE</h1>
    </aura:set>
   </aura:if>
  </lightning:card>
</aura:component>
---------------------------------------

In the above code, to get the current record we used force:hasRecordId and then we used recordId attribute which will store that value.

Next, we used Lightning data service to get the isExpired field value from the current record which we will use further in .js controller to verify if insurance is Expired or Live 

Then we used aura:if for a conditional statement to display Expired or Live status.

In case of Insurance Expired, we will ask the user to enter the insurance renewal plan and for submission, we used the Update button.

Now, let's take a look at the controller file where we are calling speech synthesis API and passing the string to speak.

What's inside controller file ->

renewInsuranceController.js
---------------------------------------
({
  doInit: function(component, event, helper) {
  var isExpired = component.get("v.record.isExpired__c");
        
  if (isExpired == true){
  component.set("v.showDetail",true);
//below code is use as speech synthesis which will accept the string and speak  
   if('speechSynthesis' in window)
    {
    var speech = new window.SpeechSynthesisUtterance('This Insurance is expired. Please renew insurance');
    speech.lang = 'en-US';
    window.speechSynthesis.speak(speech);   
     }           
    else
      {
    alert('speechSynthesis not supported');
       }
      }else if(isExpired == false){
//below code is use as speech synthesis which will accept the string and speak 
    if('speechSynthesis' in window)
    {
   var speech = new window.SpeechSynthesisUtterance('This Insurance is Live now');
    speech.lang = 'en-US';
    window.speechSynthesis.speak(speech);   
      }           
      else
      {
       alert('speechSynthesis not supported');
      }
    } 
  },
    
handleChange : function(component, event, helper) {
  var renewDate = component.get("v.renewDate");
  var recordId = component.get("v.recordId");
  var updateIns = component.get("c.updateInsurance");
        
  updateIns.setParams({
    recordId : recordId,
    renewDate : renewDate
   });
  updateIns.setCallback(this, function(response){
   var state = response.getState();
   if(state === "SUCCESS")
   {
//below code is use as speech synthesis which will accept the string and speak 
    if('speechSynthesis' in window)
    {
   var speech = new window.SpeechSynthesisUtterance('Insurance renewed successfully');
     speech.lang = 'en-US';
     window.speechSynthesis.speak(speech);   
     }           
     else
     {
     alert('speechSynthesis not supported');
     }
      component.set("v.showDetail",false);
      $A.get('e.force:refreshView').fire(); 
    }        
   });
  $A.enqueueAction(updateIns);  
  }
})
---------------------------------------

In the above code, doInit method is the one which will be called at the time of component initialization. As we want to speak out the current expiration status of insurance we will first check, isExpired field is true or false ??

If isExpired is true we are passing 'This Insurance is expired. Please renew insurance' this string to speak.

Now, web speech synthesis code here is :
-----------
if('speechSynthesis' in window)
 {
 var speech = new window.SpeechSynthesisUtterance('This Insurance is expired. Please renew insurance');
 speech.lang = 'en-US';
 window.speechSynthesis.speak(speech);   
  }           
 else
  {
  alert('speechSynthesis not supported');
 }
-----------

The above piece of code will be used to first check if your browser supports speechSynthesis of not if it supports then it will pass the string and speak through your browser audio.

In the next controller method, handleChange we are accepting the next renewal date as an input and then we are passing that to the server-side controller (apex controller) to update the End Date field of current insurance record to extend the insurance expiry.

Once we get the SUCCESS in server call we will again use the speech synthesis to speak about the successful extension of insurance.

Next, Before taking a look at the server-side controller we used 'status' and 'renewlabel' custom CSS in .cmp file let's check it out that first.

renewInsurance.css
---------------------------------------
.THIS .status {
    font-size: 2.5rem;
    text-align: center;
    font-weight: bold;
}

.THIS .renewlabel {
    color: #166161;
    background: #f1f1f1;
    text-align: center;
    font-weight: bold;
    font-size: small;
}
---------------------------------------

In the above classes, we used custom CSS to align and for the custom designing purpose to give better UI experience to the user.

Now the final one is the server-side controller (apex controller).

Create an Apex class called as 'insuranceController' and write the code as below :

insuranceController.apxc
---------------------------------------
public with sharing class insuranceController {
 @AuraEnabled
 public static void updateInsurance(Id recordId,Date renewDate)
 {
  Insurance__c ins = [Select Id,Name,End_Date__c from Insurance__c where Id=:recordId LIMIT 1];
  ins.End_Date__c = renewDate;
  update ins;
  }
}
---------------------------------------

In the above apex controller, we are just accepting the next expiry date selected by the user and updating it with current Insurance End Date. That's it.

That's it, now finally we need to change the API version to 39.0 to support speech synthesis. 


Please set the setting as above. 

And finally, now are all set Kid...


Now just go to Insurance record page and from app, builder drag the component to the right side.

Finally, it will look like:  


And when you change the End Date to less than today it will speak, when you enter next expiry date and click on successful update it will speak, When the status changed it will speak.

There you go......I am sure you will enjoy this use case and share with your fellow trailblazers and have fun.




In the upcoming episode, we will discuss a similar use case for LWC.

Wish you all the very best!!..... Happy Learning ☁️⚡️

WOHOOO !! YOU HAVE JUST COMPLETED COMPONENT THAT SPEAKS TO YOU EPISODE
If you like this SFDCkid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you all ⚡️Happy Learning ☁️⚡️ (Learn. Help. Share.) 😊 




Component That Speaks To You | Lightning Component | Salesforce Component That Speaks To You | Lightning Component | Salesforce Reviewed by on Rating: 5

3 comments:

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.