Monday, 27 January 2020

How to define design properties(attributes) in lightning web components

Hi ,

Whenever we want to provide the provision to set default values for the web components while including on different lightning page types then we use design properties. So to define design properties we have to use "@api" properties in Javascript file and we have to define design properties for the same in configuration file of lightning web component.
We can define design properties for different targets by using "targetConfig" .

Here i have configured for 2 targets
1) "lightning__AppPage"
 <targetConfig targets="lightning__AppPage">           
            <property name="title" type="string"/>
  </targetConfig>

2) "lightning__RecordPage"

 <targetConfig targets="lightning__RecordPage"> 
             <property name="title" type="string"/>         
            <property name="greeting" type="string"/>
     </targetConfig>

 The attribute "name" in <property> tag. This value must match the property name in the component’s JavaScript class.

You can define label also. It will be displayed as a label for the attribute in the tool.

Eg:
----
Calculator Example:
-----------------------
Html File:

<template>
    <lightning-card  title={title}>
        <lightning-button label="Submit" slot="actions" onclick={handleClick}></lightning-button>
        <p class="slds-p-horizontal_small">
            <lightning-input type="number" vaue={fNumber} name="fstNumber"  label="Enter First Number" onchange={handleChange} ></lightning-input>
            <lightning-input type="number" vaue={sNumber} name="scdNumber"  label="Enter Second Number" onchange={handleChange} ></lightning-input>
        </p>
        <p slot="footer">
            <b>{sum}</b>   
            <b>{greeting}</b>   
        </p>
    </lightning-card>
</template>

javascript File:
--------------------
import { LightningElement,track,api } from 'lwc';
import getSumResult from '@salesforce/apex/CalculateNumbers.getSummResult';
export default class Caclulate2Numbers extends LightningElement {
    @track fNumber;
    @track sNumber;
    @track sum;
    @track errors;
    @api title;
    @api greeting;   
    handleClick(){
        getSumResult({firstNumber:this.fNumber,secondNumber:this.sNumber})
        .then(result=>{
            this.sum = result;
        })
        .catch(error=>{
            this.errors = error;
        });
    }
    handleChange(event){
        if(event.target.name==='fstNumber'){
            this.fNumber = event.target.value;           
        }
        else if(event.target.name==='scdNumber'){
            this.sNumber = event.target.value;           
        }
    }
}

Meta File: (where we define design properties for @api variables declared in javascript)
------------
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target> 
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>     
    </targets>   
    <targetConfigs>
        <targetConfig targets="lightning__AppPage">            
            <property name="title" type="string"/>
        </targetConfig>
<targetConfig targets="lightning__RecordPage">  
             <property name="title" type="string"/>          
            <property name="greeting" type="string"/>
     </targetConfig>
    </targetConfigs> 
 
</LightningComponentBundle>

Notes:
Targets are mandatory before you define targets in <targetConfig>.

Output:
----------
While including in app page:
----------------------------------

While including in Record Page:
-------------------------------------


Reference:
https://www.youtube.com/watch?v=G7oJDD6RMWU&list=PL-JzyFWuCbkKcFSOCRlCUk79YbET5QvZC

https://developer.salesforce.com/docs/component-library/documentation/lwc/reference_configuration_tags

Saturday, 25 January 2020

Data Retrieval – imperative Apex method call

Hi,
Lightning web components can import methods from Apex classes. The imported methods are functions that the component can call either via @wire or imperatively.

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

Now our example is how to call a method imperatively. here is the code:
HTML:
<template>
    <lightning-datatable data={accountRecords} key-field="id" columns={columns}></lightning-datatable>
</template>

Javascript:

import { LightningElement,track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccountRecordsList';

export default class DataDisplayWithImperative extends LightningElement {
    @track accountRecords;
    @track errors;
    @track columns = [{label:'Name',fieldName:'Name',type:'text'},
    {label:'Industry',fieldName:'Industry',type:'text'},];
    connectedCallback(){
        getAccounts()
            .then(result=>{
                this.accountRecords = result;
            })
            .catch(error=>{
                this.errors = error;
            });
    }
}


Meta File:
---
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__Tab</target>
    </targets>
</LightningComponentBundle>


output:
------

References:


Tuesday, 31 December 2019

Passing parameters to apex class from LWC with imperative method

Hi ,

I am going to explain how to pass two parameters into an apex class method using imperative method.

Apex Class:
public with sharing class CalculatorController {
    public CalculatorController() {

    }
    @AuraEnabled(cacheable=true)
    public static Integer calculate2Numbers(integer firstNumber,integer secondNumber){
     
        return (firstNumber+secondNumber);
    }
}


HTML File (Template):

<template>
   <lightning-card title="Calculator with apex class" icon-name="custom:custom63">
      <p class="slds-p-horizontal_small">
        <lightning-input label="First Number" name="fNumber" type="number"
value={fNumber} onchange={handledChange}></lightning-input>
        <lightning-input label="Second Number" name="sNumber" type="number"
value={sNumber} onchange={handledChange}></lightning-input>
        <lightning-input label="Result" type="number" value={resultsum}>
</lightning-input> </br>
        <lightning-button label="Submit" onclick={handleClick}>
</lightning-button>
       </p>
    </lightning-card>
</template>



Javascript File:

The below javascript file has example to invoke method from apex class:
Syntax:
import <nameofthemethod> from '@salesforce/apex/<apex class Name>.<methodName>'
import { LightningElement,wire,trackfrom 'lwc';
import calculate2Numbers from '@salesforce/apex/CalculatorController.calculate2Numbers';
export default class Calculatorwithapex extends LightningElement {
    fNumber;
    sNumber;
    @track resultsum;
    handledChange(event){
        if(event.target.name==='fNumber'){
            console.log('handle Change'+event.target.value);
            this.fNumber = event.target.value;
        }
        else if(event.target.name==='sNumber'){
            console.log('handle Change'+event.target.value)
            this.sNumber = event.target.value;    
        }
       
    }
    handleClick(){
        console.log('hi::button invoked'+this.fNumber+'--'+this.sNumber);
        calculate2Numbers({ firstNumber: this.fNumber,secondNumber:this.sNumber })
        .then(result => {
            this.resultsum = result;
            console.log('hi::'+result);
           // this.error = undefined;
        })
        .catch(error => {
            this.resultsum = undefined;
            //this.error = error;
        });
        
    }
   
   
   

}



Meta File (Configuration File):
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__Tab</target>
    </targets>    
</LightningComponentBundle>

Referece:
https://www.youtube.com/channel/UCipDch4PvPqm0uY4SK7mi1A

Tuesday, 24 December 2019

Defining public properties and communication between parent to child component

Hi,

We are going to see a small example with @api decorator. It will be useful for defining properties and methods public.

To expose a public property, decorate it with @api. Public properties define the API for a component. An owner component that uses the component in its markup can access the component’s public properties. Public properties are reactive. If the value of a reactive property changes, the component rerenders. When a component rerenders, all the expressions used in the template are reevaluated.

To expose a public method, decorate it with @api. Public methods are part of a component’s API. To communicate down the containment hierarchy, owner and parent components can call JavaScript methods on child components.

Let's see small example here which can be ready to accept values from other components:

HTML file:(resultComponent.html)
<template>
    <div>Addition Result:{result}</div>
</template>

JavaScript file:(resultComponent.js)
import { LightningElement,api } from 'lwc';

export default class ResultComponent extends LightningElement {
    @api result;
}

Configuration file:(resultComponent.js-meta.xml)

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>           
    </targets>
</LightningComponentBundle>


You can pass the values to "result" property with decorator @api from another component. You have to kebab case to include the component and its properties. 
<c-result-component result={result}></c-result-component> 

I am adding this to the calculator example as shown below.

<template>
    <lightning-card>
        <h3 slot="title">
            <lightning-icon icon-name="utility:connected_apps" size="small">
</lightning-icon>
            Calculator Example
        </h3>
        <div slot="footer">
                <!--lightning-badge label={result}></!--lightning-badge-->  
                <c-result-component result={result}></c-result-component> 
        </div>
        <p class="slds-p-horizontal_small">
            <lightning-input value={firstNumber} name="fnumber" 
label="First Number" onchange={handleChanges}></lightning-input>
            <lightning-input value={secondNumber} name="snumber" 
label="Second Number" onchange={handleChanges}></lightning-input>

        </p>
    </lightning-card>
</template>



Reference:
https://developer.salesforce.com/tv/lwc-video-gallery/
https://developer.salesforce.com/docs/component-library/documentation/lwc/js_props_public
https://github.com/trailheadapps/lwc-recipes/blob/master/force-app/main/default/lwc

Tuesday, 17 December 2019

Simple Calculator Example with Lightning Web Components

Hi ,

Here let's talk about a simple example of a Calculator with a track decorator. @track decorator should be where we need to re-render the changes of a property to the template (HTML file) in the Lightning Web component only but not for all properties.
in the following, we are decorating only one property "result" with "track".

Let's see three files how it looks like. Here we are using  <lightning-card> also for UI design.

calculator.html


<template>
    <lightning-card>
        <h3 slot="title">
            <lightning-icon icon-name="utility:connected_apps" size="small"></lightning-icon>
            Calculator Example
        </h3>
        <div slot="footer">
                <lightning-badge label={result}></lightning-badge>                
        </div>
        <p class="slds-p-horizontal_small">
            <lightning-input value={firstNumber} name="fnumber" label="First Number" onchange={handleChanges}></lightning-input>
            <lightning-input value={secondNumber} name="snumber" label="Second Number" onchange={handleChanges}></lightning-input>

        </p>
    </lightning-card>
</template>


calculator.js


import { LightningElement,track } from 'lwc';

export default class CalcTest extends LightningElement {
    firstNumber=0;
    secondNumber=0;
    @track result=0;
    handleChanges(event){
        if(event.target.name==='fnumber'){
            this.firstNumber= event.target.value;
        }
        if(event.target.name==='snumber'){
            this.secondNumber= event.target.value;
        }
        this.result = parseInt(this.firstNumber)+ parseInt(this.secondNumber);
    }
}
calculator.js-meta.xml


<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>47.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>        
    </targets>
</LightningComponentBundle>


Output:


References:
https://www.youtube.com/channel/UCipDch4PvPqm0uY4SK7mi1A
https://developer.salesforce.com/tv/lwc-video-gallery/
https://developer.salesforce.com/docs/component-library/documentation/lwc/reference_decorators
https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.js_props_private_reactive

https://developer.salesforce.com/docs/component-library/documentation/lwc/reference_decorators

Friday, 13 December 2019

Supported Salesforce Experiences and Tools for Lightning Web Components

Hi,

Lightning web components are supported in many Salesforce experiences and tools. To use a Lightning web component with an unsupported experience or tool, wrap it in an Aura component.

These Salesforce experiences and tools are supported.


  • Lightning Experience
  • Salesforce App
  • Lightning Communities
  • Lightning App Builder
  • Community Builder
  • Standalone Apps
  • Lightning Components for Visualforce
  • Lightning Out (beta)
  • Custom Tabs
  • Utility Bars
  • Flows
  • First-Generation Managed Packages
  • Second-Generation Managed Packages
  • Unlocked Packages
  • Unmanaged Packages
  • Change Sets
  • Metadata API—LightningComponentBundle
  • Tooling API—LightningComponentBundle, LightningComponentResource
  • EMP API
  • Embedded Service Chat
  • Gmail and Outlook integration
Unsupported Experiences and Tools

Lightning Web Components doesn’t currently support these Salesforce experiences and tools. To use a Lightning web component with these experiences and tools, wrap the component in an Aura component.

  • Salesforce Console APIs (Navigation Item API, Workspace API, Utility Bar API)
  • URL Addressable Tabs
  • Conversation Toolkit API, Omni Toolkit API, Quick Action API
  • Standard Action Overrides, Custom Actions, Global Actions, List View Actions, Related List View Actions
  • Chatter Extensions

NOTE Salesforce Mobile SDK doesn’t support Lightning Web Components. The workaround of wrapping a Lightning web component in an Aura component is also unsupported.


Reference:

https://developer.salesforce.com/docs/component-library/documentation/lwc/get_started_supported_javascript


Thursday, 12 December 2019

Defining a Property in Lightning Web Component

Hi ,

I am going to explain a simple example about a property and render the value of it on HTML file of lightning web component.

As we know we have three main files required for any lightning web component. Those are
HTML ,Javascript,Meta files.

Lets have a simple Helloworld example:

When you create lightning web component with the name "helloworld" it creates the Lightning Web Component bundle with three basic required files as shown below.


Let's write a simple html markup in
"helloworld.html". Here <template> is root tag always.

<template>
    <lightning-card title="HelloWorld" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <p>Hello, {greeting}!</p>
            <lightning-input label="Name" value={greeting} onchange={changeHandler}></lightning-input>
        </div>
    </lightning-card>
</template>

Let's define property "greeting" with @track decorator in java script file "helloworld.js"

import { LightningElementtrack } from 'lwc';
export default class HelloWorld extends LightningElement {
    @track greeting = 'World';
    changeHandler(event) {
        this.greeting = event.target.value;
    }
}

here "@track" decorator makes your property reactive and render the changes on html file

in java script we have one property "greeting" with "@track" decorator and one function "changeHandler" where we set the value to property for any change from "lightning-input".

Now  let's look at meta file (configuration file): helloworld.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="Helloworld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>


In meta file we can maintain the configurations of Lightning Web Components.
The configuration file defines the metadata values for the component, including the design configuration for Lightning App Builder and Community Builder.

Here we have the following things:
<apiVersion> :A double value that binds the component to a Salesforce API Version.

<isExposed> : It can be used to expose our component to App Builder or Community Builder.
If isExposed is false, the component is not exposed to Lightning App Builder or Community Builder.
To allow the component to be used in Lightning App Builder or Community Builder, set isExposed to true and define at least one <target>, which is a type of Lightning page.

<targets>:
Specifies where the component can be added, such as on a type of Lightning Page or in Embedded Service Chat. If you want your component to appear in the Lightning App Builder or in Community Builder, specify at least one Lightning page type.

Here our component exposed to "App page,Record Page,Home Page" of App Builder.

Output:






Whatever we type in input it immediately renders to "greeting" property because "@track" decorator.

Reference:
https://www.youtube.com/channel/UCipDch4PvPqm0uY4SK7mi1A
https://developer.salesforce.com/docs/component-library/documentation/lwc

Wednesday, 11 December 2019

What Lightning Web Component Requires?

Hi,


Lightning Web Components is a new programming model for building Lightning components. 

Every Lightning Web Component requires the following files:

  • HTML File - which has markup and renders UI
  • Javascript File - which has  logic and properties 
  • Meta File - which has component information about where it has to be exposed
  • CSS File (Optional)
  • SVG (Optional)

HTML File:


 Javascript File:

                                          

Meta File
                                     





References:

Sunday, 8 December 2019

Javascript Decorators of Lightning Web Component

Hi ,

Decorators add functionality to property or function. The ability to create decorators is part of ECMAScript, but the following decorators are unique to Lightning Web Components.

  • @track
  • @api
  • @wire

@track

Private properties that contain a primitive value are reactive. If a reactive property is used in a template and its value changes, the component re-renders.

If a private property contains an object, to mark is as reactive, annotate it with @track. LWC tracks changes on the object's properties. If a property is used in a template and its value changes, the component re-renders.


@api



To expose a public property, decorate it with @api. Public properties define the API for a component. To communicate down the component hierarchy, an owner component can access and set a child component’s public properties.
Public properties are reactive. If the value of a reactive property changes, the component’s template renders any content that references the property. For more information, see Public Properties.To expose a public method, decorate it with @api.
Public methods also define the API for a component. To communicate down the component hierarchy, owner and parent components can call JavaScript methods on child components.

@wire

It will be used to read Salesforce data, Lightning web components use a reactive wire service. When the wire service provisions data, the component rerenders. Components use @wire in their JavaScript class to specify a wire adapter or an Apex method.


Referece:


Thursday, 28 November 2019

Prepare email message with Template using renderStoredEmailTemplate method

Hi ,



When we have to use email template then we have to use few methods like "setTemplateId" ,"setWhatId" etc.


But we can use single method "renderStoredEmailTemplate"to  prepare the message from email template. We have to be careful when we use this method because it counts SOQL query.


Eg:

Messaging.SingleEmailMessage message = Messaging.renderStoredEmailTemplate(templateid,whoId,whatId);
message.setsaveAsActivity(false);
Messaging.sendEmail(new List<Messaging.Email>{message});




Reference:
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_email_outbound_messaging.htm

Saturday, 7 September 2019

How to restrict your component to one or more objects?

Hi ,

We can restrict to our component to one or more objects by using the following:

<sfdc:objects> and <sfdc:object>

Here in the following example we are restricting the component to Opportunity which is using the following design component by using  <sfdc:objects> and <sfdc:object>.


<design:component label="Hello World">
    <design:attribute name="subject" label="Subject"/>
    <design:attribute name="greeting" label="Greeting" />    
    <sfdc:objects>       
        <sfdc:object>Opportunity</sfdc:object>
    </sfdc:objects>
</design:component>

If we define the design component with lightning component as above then it will be available for Opportunity Lightning Record page only.

Reference:

How to define design properties(attributes) in lightning web components

Hi , Whenever we want to provide the provision to set default values for the web components while including on different lightning page t...