Saturday, 30 January 2021

 @wire with dynamic parameters

Call to apex method using @wire is executed at the time component loads. But suppose we want to make server call when a particular parameter changes.

So for that we can @wire an apex method with a dynamic parameter. We need to pass a parameter with “$” appended to it while making call to apex method. So, once the value of this property changes, call to apex is made at that time.

Apex class

public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContactList(){
    List<Contact> contactList = [SELECT id,lastName from contact LIMIT 10];
    return contactList;
}
}

html

<template>
<lightning-card title="wire with dynamic paramters" icon-name="custom:custom19">
<!-- Show contact if end-->
<lightning-input type="checkbox" label="Show Contacts Details" checked={showContacts} onchange={handleFlag}>
</lightning-input>

<!-- Show contact if check-->
<template if:true = {showContacts} icon-name="standard:contact">
<template for:each={conList} for:item="contact">
        <p key = {contact.LastName} >
            contact name : {contact.LastName}
        </p>
    </template>
</template>
</lightning-card>
</template>

js

import { LightningElement,wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList'
export default class DynamicProperty extends LightningElement {
    conList ;
showContacts = false;

handleFlag(event){
    this.showContacts = event.target.checked;

}
@wire (getContactList,{flag : '$showContacts'})
contactList({error,data}){
    if(error){
        console.log('error is-->'+error);

    }
    else if(data){
        this.conList = data;
    }

}

xml

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

Saturday, 16 January 2021


Access Client Form Factor

To access the form factor of the hardware the browser is running on, import the @salesforce/client/formFactor scoped module.

import formFactorPropertyName from '@salesforce/client/formFactor'

  • formFactorPropertyName—A name that refers to the form factor of the hardware running the browser. Possible values are:
    • Large—A desktop client.
    • Medium—A tablet client.
    • Small—A phone client.
html
<template>
    <lightning-card title="formfactorName" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            <p>FormFactor:</p>
            {formFactor}
        </div>
    </lightning-card>
</template>

js
import { LightningElement } from 'lwc';
import FORM_FACTOR  from '@salesforce/client/formFactor'
export default class ClientFormFactor extends LightningElement {

    formFactor = FORM_FACTOR;
}

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

Get Information About the Current User

To get information about the current user, use the @salesforce/user scoped module.

import property from '@salesforce/user/property';

  • property—The supported properties are Id, which is the user’s ID, and isGuest, which is a boolean value indicating whether the user is a community guest user. Use the isGuest property to check whether or not the user is authenticated.

This sample code imports the current user ID and assigns it to the userId property to provide access in the HTML template.

html

<template>
    <lightning-card title="currentuserId" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            <p>User Id:</p>
            {userId}
        </div>
    </lightning-card>
</template>

js

import { LightningElement } from 'lwc';
import Id from '@salesforce/user/Id';
export default class CurrentUser extends LightningElement {
    // Assign to variable
    userId = Id;
}

xml

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

</LightningComponentBundle>

Tuesday, 12 January 2021

   Access Static Resources in LWC

Import static resources from the @salesforce/resourceUrl scoped module. Static resources can be archives (such as .zip and .jar files), images, style sheets, JavaScript, and other files.

import myResource from '@salesforce/resourceUrl/resourceReference';

import myResource from '@salesforce/resourceUrl/namespace__resourceReference';
  • myResource—A name that refers to the static resource.
  • resourceReference—The name of the static resource.

A static resource name can contain only underscores and alphanumeric characters, and must be unique in your org. It must begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.

  • namespace—If the static resource is in a managed package, this value is the namespace of the managed package.

Let’s look at some sample code.

Explanation

  •  Created static resource named 'Testphoto' .
  • Referred static resource in Javascript : @salesforce/resourceUrl/Testphoto

html

<template>
    <lightning-card title="My image" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            <img src={dispPhoto}>
        </div>
    </lightning-card>
</template>

Javascript

import { LightningElement } from 'lwc';
import Testphoto from '@salesforce/resourceUrl/Testphoto'
export default class StaticResourceAccess extends LightningElement {
    dispPhoto = Testphoto;
}

xml

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

Sunday, 10 January 2021

Usage of utility classes in Lightning web component:

In this demo, explaining about the usage of utility classes in Lwc. I have created utility class inside the  component folder. Utility class name is "Utilityhelper".

Utility helper is referred in component of JavaScript Like below :

import {add,subfrom './utilityhelper.js';

Complete code Snippet:

shareCode.html

<template>
    <lightning-card title="Usage of Javascript Utility Classes">
    <p> add : {resultFromHelper} </p>
    <p> sub : {substractVal} </p>
</lightning-card>
</template>

Javascript

import { LightningElement } from 'lwc';
import {add,subfrom './utilityhelper.js';
export default class UtilityComponent extends LightningElement {
    resultFromHelper;
    substractVal ;
    constructor(){
        super();
        const result = add(1,9);
        this.resultFromHelper=result;
        this.substractVal=sub();
 }
}

xml

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

utilityhelper

/** helper class */
function add(a,b){
  return a+b;

}

function sub(a,b){
  return 5-3//Hardcoded 
}
export{add,sub};

Saturday, 9 January 2021

                                 Calling Child Component Method Using Parent :

Example  shows how to call child component method from parent using template.querySelector.

  • findLegend -> Method in childComponent
  • Master Blaster Sachin Tendulkar -> Its parameters passing to findLegend Method
  • In this child component method, findLegend method exposed as api method property.

ParentComponent4.html

<template>
    <lightning-card title="Calling child comp from Parent method" icon-name="custom:custom14">
        <c-child-component4 ></c-child-component4>
    <lightning-button label="Find Cricket Legend Name"
                      onclick={fireEvent}
    >
    </lightning-button>
</lightning-card>
</template>

Js

import { LightningElement } from 'lwc';

export default class ParentComponent4 extends LightningElement {
    //Calling child method 
    fireEvent(){
        //Calling child method from parent
        this.template.querySelector("c-child-component4 ").findLegend('Master Blaster Sachin Tendulkar');

    }
}

xml:

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

childComponent4.html

<template>
  
    <p> Do you would like to know whos the legend of cricket? </p> <br/> 
    <b> Click on below button to get Legend Name</b>  <br/> 
     <p> Legend Name: <b> {cricketerName} </b></p>
</template>

Js

import { LightningElement,api } from 'lwc';

export default class ChildComponent4 extends LightningElement {
    @api cricketer;
    cricketerName;
    //Decorate method with apI property
    //Publicly expose this method
    //Otherwise it becomes private method
    @api findLegend(Name){
       this.cricketerName =Name;
    }
}

xml

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

                                         Configuration File Tags

apiVersion:- A double value that binds the component to a Salesforce API version. To check the current version, take help of this knowledge article.

description:-A short description of the component, usually a single sentence. Appears in list views, like the list of Lightning Components in Setup, and as a tooltip in the Lightning App Builder and in Community Builder.

When you hover your mouse to the custom component deployed to the org, you can see the description with the label.

isExposed:-A Boolean value. Exposes the component in all orgs, and in Lightning App Builder and Community Builder. To make a component usable in a managed package, set isExposed to true. To make a component usable in Lightning App Builder and Community Builder, set isExposed to true.

masterLabel:-The title of the component. Appears in list views, like the list of Lightning Components in Setup, and in the Lightning App Builder and in Community Builder.

targetConfig:- It is subtag of targetConfigs and used for different page type configuration. For Example:-

<targetConfig targets=”lightning__RecordPage”>

<targetConfig targets=”lightning__AppPage, lightning_HomePage”>

targets:-The targets attribute value that you specify must match one or more of the page types that you listed under <targets> for the component. It Supports the property and objects subtags.

property:-Specifies a public property of a component that can be set in Lightning App Builder or Community Builder. The component author defines the property in the component’s JavaScript class using the @apidecorator.

objects:-A set of one or more objects the component is supported for. This tag set works only inside a parent targetConfig that’s configured for lightning__RecordPage. Specify the objects tag set only once inside a targetConfig set. Supports the object subtag.

 Note

object:-Defines which objects the component is supported for. Use one object tag for each supported object. You can’t use ‘*’ to denote all objects.

 

Html

<template>
    <div class="slds-m-around_small">
        <strong>
            Metadata File Example {message} <br/>
            page no  : {pageno}
        </strong>
    </div>
</template>

Javascript

import { LightningElement,api } from 'lwc';

export default class MetaExample extends LightningElement {
    @api message;
    @api pageno;
}

xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
     <isExposed>true</isExposed>
    <masterLabel>Metadata File Configuraton</masterLabel>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
        <target>lightningCommunity__Default</target>
        <target>lightningCommunity__Page</target>
        <target>lightning__Tab</target><!-- Winter 20 -->
        <target>lightning__Inbox</target>
    </targets>
    <targetConfigs>
        <targetConfig targets="lightning__RecordPage" >
            <property name="message" type="String" label="Welcome Message"/>
            <property name="pageno" type="Integer" label="Page No" />
            <objects>
                <object>Contact</object>
              </objects>
        </targetConfig>
    </targetConfigs>
</LightningComponentBundle>