Lightning

Child to Parent Communication in LWC

For a child component to communicate with parent component, A child component dispatches a custom event that triggers an update in the parent component. While sending an event to parent component, you can choose to send data and you can allow the event to bubble up through DOM. Along with an event, you can send custom information and make use of that information to update something.

Parent to Child communication

If you have used custom lookup component in LWC, this component works on Child to Parent communication, where a user selected record is dispatched as an event to parent component where it is captured and shown as a pill. This is just a small example.

In this blog we will see how to use the custom event method with a small example.

We have 2 components here

1)Parent component
2)Child component

parent.html

<template>
    <lightning-card  title="Hello this is Papa Cpmponent">
        
        <p class="slds-p-horizontal_small">
            <lightning-input  type="text" label="Name" value={Name} read-only="true" ></lightning-input>
            <lightning-input  type="text" label="Actor" value={Actor} read-only="true" ></lightning-input>
            <lightning-input  type="text" label="Movie" value={Movie} read-only="true" ></lightning-input>
            <lightning-input  type="text" label="Punchline" value={Punchline} read-only="true" ></lightning-input>

        </p>

        <div slot="footer">
            <div class="slds-grid slds-gutters">
                <div class="slds-col">
                    <c-child-comp child-name="Raju" oncharacterinfo={handle_Details}> 
                    </c-child-comp>
                </div>
                <div class="slds-col">
                    <c-child-comp child-name="Vicky" oncharacterinfo={handle_Details}> 
                    </c-child-comp>
                </div>
                <div class="slds-col">
                    <c-child-comp child-name="Baburao" oncharacterinfo={handle_Details}> 
                    </c-child-comp >
                </div>
              </div>
        </div>
    </lightning-card>
</template>

parent.js

import { LightningElement } from 'lwc';

export default class Papa extends LightningElement {
    Name;
    Actor;
    Movie;
    Punchline;

    handle_Details(event){
        
        console.log(JSON.stringify(event.detail));
        
        this.Name = event.detail.a_Name;
        this.Actor = event.detail.a_Actor;
        this.Movie = event.detail.a_Movie;
        this.Punchline = event.detail.a_Punchline;

        console.log ('-=-= name: '+this.Name);
        
    }
}

If you observe papa.html file. I have used a lightning card, with body and footer.

The body part will only display details that we receive from child component

Footer part has child components which is used 3 times representing 3 different movie character.

childComp.html

<template>
    <lightning-card  title={childName}>
        
        <lightning-button 
            variant="brand"
            label="Check Details" 
            onclick={handleClick} 
        ></lightning-button>
        
    </lightning-card>
</template>

childComp.js

import { LightningElement,api } from 'lwc';

export default class ChildComp extends LightningElement {
    @api childName = '';
        
        Name = '';
        Actor = '';
        Movie = '';
        Punchline = '';
    
        handleClick(event){
            console.log('child click event: '+event);
    
            
    
    
            switch (this.childName) {
                case 'Raju': 		
                    
                this.Name = 'Raju';
                this.Actor = 'Akshay Kumar';
                this.Movie = 'Hera Pheri';
                this.Punchline = 'Paisa hi paisa hoga!';
                
                break;
    
                case 'Vicky': 	
                    
                this.Name = 'Vicky Chopra';
                this.Actor = 'Amitab Bachchan';
                this.Movie = 'Sharabi';
                this.Punchline = 'Mooche Ho Toh Nathulal Ji Jaise Ho... Varna na ho';
                    
                break;
            
                case 'Baburao': 		
                    
                this.Name = 'Baburao Ganpatrao Apte';
                this.Actor = 'Phir Paresh Rawal';
                this.Movie = 'Hera Pheri';
                this.Punchline = 'Uthala le re baba';
                    
                break;
                
                default: 
    
                break;
                
            }
    
            console.log('-=-= in child: '+this.Name);
            console.log('-=-= in child: '+this.Movie);
            console.log('-=-= in child: '+this.Actor);
            console.log('-=-= in child: '+this.Punchline);
    
            const a_Name = this.Name;
            const a_Movie = this.Movie;
            const a_Actor = this.Actor;
            const a_Punchline = this.Punchline;
    
            const selectedCharacter = new CustomEvent('characterinfo', {
                detail: {
                    a_Name,
                    a_Movie,
                    a_Actor,
                    a_Punchline
                },
            });
            this.dispatchEvent(selectedCharacter);
    
        }
}

If you see child component’s html part. I have just added a button to click and get details.

In childComp.js file, button click event, Based on name of the child component, details will be fetched using switch statement.

This is the place where you can add custom code and make some server calls to get any other details as per requirement.

I have used a constant called selectedcharacter which is a custom event.

const selectedCharacter = new CustomEvent('characterinfo', {
                detail: {
                    a_Name,
                    a_Movie,
                    a_Actor,
                    a_Punchline
                },
            });
            this.dispatchEvent(selectedCharacter);

here, if you observe ‘characterinfo’ that is the event name, you can replace it with any character that you want. Any name that you use in child component, in parent you must have an on as an event

If you observe how the component is called in parent component,

<c-child-comp child-name="Raju" oncharacterinfo={handle_Details}> 
                    </c-child-comp>

name of the component is saved as childComp. while using the component in a parent component, there will be no CAPITAL case for any character, if there is a Capital case, it will be replaced with -<small case of same character>. In above example, childComp, here C is capital so while using in parent compnent, we have to mention -c. that is the reason we have used <c-child-comp >

oncharacterinfo ={handle_Details} is used for custom event details. If you use custom event as moviecast, then in parent component you must use onmoviecast as event name and call a method to handle that event.

If you observe the child component, you see detail as a variable, this is a event property, you can also use details as event property. Please note, you cannot use any other variable, you have to be specific and it should be one of the property of event.

Output

Lightning

Using Helper in Lightning Web Component (LWC)

If you have worked on Aura component, you may know how important helper JS file in Lightning Aura Component is. Helper class helps you to reuse a method in any main class. It also helps you to keep main JS file clean.

Salesforce always recommends making best use of helper class. All logic should be written in helper class with proper naming conventions. And main JS file should just call the helper methods.

In this post we will see how we can make use of helper class in Lightning Web Component. I am completely new to this topic I may not give all the information in this post. However, I will give you some basic information.

Let us see basic example of adding 2 numbers using helper class.

HTML File

<template>
    <div class="slds-box slds-theme_default"> 
        <lightning-input type="number" variant="standard" name="Value1" label="value 1" value={value1} onchange={handle_Value1_change} ></lightning-input>
        <lightning-input type="number" variant="standard" name="Value2" label="value 2" value={value2} onchange={handle_Value2_change}></lightning-input>

        <lightning-button variant="brand" label="SUM" title="SUM" onclick={handleClick}></lightning-button>
        {result}
    </div>
</template>

Main JS File.

import { LightningElement } from 'lwc';
import {sayHello, add} from './SampleDemoHelper';

export default class SampleDemo extends LightningElement {

    value1;
    vault2;
    result;

    connectedCallback(){
        console.log('Hello from main SampleDemo');
        sayHello('Akhil Kulkarni');
    }


    handle_Value1_change(event){
        this.value1 = event.target.value;
    }

    
    handle_Value2_change(event){
        this.value2 = event.target.value;
    }


    handleClick(event){

        var sum = add(this.value1, this.value2);
        this.result = "SUM of " + this.value1 + " and " + this.value2 +" is: "+ sum;
    }
}

Helper JS File.

export function sayHello(a_Name){
    console.log('Hello from SampleDemoHelper to: '+a_Name);
}


export function add(val1,val2){
    return parseFloat(val1) + parseFloat(val2);
}

You can create a helper JS file in any name, there are no specifications for that. It is good practice to use helper class with a simple naming just to follow LAC naming convention that is helper.js

For instance, I have created a LWC as SampleDemo then my helper class name will be SampleDemoHelper.js

Please note you can create multiple helper classes and give different names. I have tried above example with just one helper class.

All helper class methods are like individual separate methods. They do not have access to any of the variables which are in main JS or any other JS file.

For instance, as a developer as use this.variable name in main JS file. We do not have access to those variables. Treat this helper as a separate method which has no access to variables outside world. You can pass various parameters write business logic and return the value.

You need to append the key word export to all the functions. This means that you are exposing the
helper method. Exposing is not the only step. You also need to mention which methods you will be using in main JS file.

import {sayHello, add} from './SampleDemoHelper';

This means, we are going to use 2 methods sayHello and add which are defined in SampleDemoHelper file. You can define multiple methods which can be used in other components as well. and you have to import those methods which will be used in current component.

OUTPUT:

Lightning

LWC: lightning-input-address custom validation

It is common practice to use lightning-input-address tag to fetch address information from user. However, sometimes we much show validation to one field or we must show a custom validation message. To achieve this functionality, we use the code below.

 <lightning-input-address 
    address-label="" 
    show-address-lookup="true"
    street-label="Street" 
    city-label="City" 
    country-label="Country" 
    province-label="State/Province" 
    postal-code-label="Postal Code" 
    country-options={getCountryOptions_For_Contact}
    province-options={getProvinceOptions_For_Contact}
    onchange={handle_Check_Validation} 
    address-lookup-placeholder="Search address...">
</lightning-input-address>

the above code also has global search lookup feature.

To handle to validation functionality and to display error message on specific field. we user below code. as part of example I will just show you one field. validation and similar can be implemented for rest of the fields.

As part of example I will show validation on country field. Let us say that country is always required even if user does not enter full address, atleast country should be selected.

handle_Check_Validation(event) {
	const address = this.template.querySelector('lightning-input-address');
	//Country Field Validation
	var country = address.country;
	if (!country) {
		address.setCustomValidityForField("Complete this field.", "country");
	} else {
		address.setCustomValidityForField("", "country"); //Reset previously set message
	}
    address.reportValidity();
}

Here there are 2 piece of code that we need to consider.
1)setCustomValidityForField()
2)reportValidity()

setCustomValidityForField()
Sets a custom error message to be displayed for the specified fieldName when the input address value is submitted.
This method takes 2 parameters namely Message and FieldName
Message – The string that describes the error. If message is an empty string, the error message is reset.
FieldName – Name of the field, which must be one of the following: street, city, province, postalCode, country.

reportValidity()
Displays the error messages and returns false if the input is invalid. If the input is valid, reportValidity() clears displayed error messages and returns true.

Note:

  1. reportValidity() is important, if that is missed then validation message is not alerted to end user.
  2. You can use this code in onsubmit method as well.

Output:

Reference

Salesforce: lightning-input-address

Lightning · Salesforce Basic

AURA: Updated URL Parameter Value in JS File

I was working on a page in Aura component and the page is loaded on click of a button from a related list(It can also load from a quick Action button). AURA components have a behavior that a component loads with value in cache memory. Which means, AURA component can sometimes load the previously clicked value from URL. Behavior is unpredictable. Which means, Component can load updated value or it can also load previous URL parameter value. For which user may have to click refresh button to load new info.

Continue reading “AURA: Updated URL Parameter Value in JS File”
Lightning

LWC: Lightning-Combobox required field validation on submit button

When working with custom Lightning-combobox in LWC most of the time you will face problems making combo box a required field. When using a Lightning-record-edit-form, you usually use lightning-input-field tag and it takes care of all the FLS (Field Level Security) and irrespective of field type it handles every type of field. However, there will be scenarios where lightning-input-field may not be suitable and end up using a custom tag. For instance, a custom lookup field or multi select custom lookup field or a custom record type selection combo box. You end up using a custom solution for these.

Continue reading “LWC: Lightning-Combobox required field validation on submit button”