Showing posts with label HTML. Show all posts
Showing posts with label HTML. Show all posts

Thursday, 24 February 2022

[Resolved:] Set value of the picklist field for the selected records to mass update in lightning web component.

SCENARIO 

While working on one of the requirements for a manufacturing sector solutions customer based out in Dallas, Texas there was a requirement to set selected value of picklist field to mass update of records in lightning web component.

CHALLENGE 

We have achieved this functionality of setting the value of picklist by creating  custom lightning web component. We have used custom javascript functions to update mass records. 

However, we got stuck with the issue of updating records for the selected value. 

APPROACH

To fulfill this requirement,we decided to create custom javascript functions to select multiple files and to assign values to each files. 

Below is a sample code for reference.

HTML Code:-

    <template>
      <lightning-card title="Account List"> 
        <div class="slds-m-around_medium" >

        
        <div class='slds-grid slds-gutters'>
          <div class='slds-col'>
            <lightning-input type="checkbox" onchange={handleSelectAllIndustryChk}
                             label="Select All" data-id="selectAllIndustry">
          </lightning-input>

          </div>
         </div>
         <template for:each={accounts} for:item="account" for:index="index">
          <div class='slds-grid slds-gutters' key={account.Name}>
            <div class='slds-col slds-m-top_large slds-size_1-of-7'>
              <lightning-input type="checkbox" name={account.Name} data-class="cus_IndustryHelper"
              onchange={handleIndustryCheckbox} data-id='IndustryTypeChk'>
              </lightning-input>
              </div>
              <div class='slds-col slds-size_3-of-7'>
                <lightning-input label="Account Name" type="text" value={account.Name}
                                  disabled="true">
                </lightning-input>
              </div>
              <div class='slds-col slds-size_3-of-7'>
                <lightning-combobox name={account.Name} label="Industry" data-id={account.Name}
                                    class="picklistContent"  dropdown-alignment="auto"
                                    placeholder="Select account Type" options={IndustryPicklist.data.values}
                                    onchange={handleIndustrySelectionChange} required>
                </lightning-combobox>
              </div>
          </div>
        </template>
      </div>
      </lightning-card>  
    </template>    
  

JavaScript Code:-

import { LightningElement, api, wire, track } from 'lwc';
import AccountList from '@salesforce/apex/AccountController.AccountList';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import Account_OBJECT from '@salesforce/schema/Account';
import Industry_FIELD from '@salesforce/schema/Account.Industry';
   
export default class DataTableInLwc extends LightningElement {
    
    @track accounts=[];
    @track selectedIndustryValues=[];
    
    

  @wire(AccountList)
  wiredfiles(result){
      
      if(result.data){
          this.accounts=result.data;
          
      }
      else{
          console.log('Data not found');
      }
    }


    @wire(getObjectInfo, { objectApiName: Account_OBJECT })

    AccountMetadata;

    @wire(getPicklistValues,

        {

            recordTypeId: '$AccountMetadata.data.defaultRecordTypeId',

            fieldApiName: Industry_FIELD

        }

    )

    IndustryPicklist;
    
   

    handleSelectAllIndustryChk(event) {
    this.selectedIndustryValues = [];
    var checkboxes = this.template.querySelectorAll('[data-id="IndustryTypeChk"]');
    for (var i = 0; i < checkboxes.length; i++) {
        checkboxes[i].checked = event.target.checked;
        event.target.checked ? this.selectedIndustryValues.push(checkboxes[i].name) : '';
        }
    }

        
        handleIndustryCheckbox(event) {
            if (event.target.checked) {
                this.selectedIndustryValues.push(event.target.name);
                let checkboxes = this.template.querySelectorAll('[data-class="cus_IndustryHelper"]');
                let length = 0;
                for (var i = 0; i < checkboxes.length; i++) {
                    (checkboxes[i].checked == true) ? length = length + 1: length = length - 1;
                }
                ((checkboxes.length) == length) ? this.template.querySelectorAll('[data-id="selectAllIndustry"]')[0].checked = true: this.template.querySelectorAll('[data-id="selectAllIndustry"]')[0].checked = false;
            } else {
                this.selectedIndustryValues.splice(this.selectedIndustryValues.indexOf(event.target.name), 1);
                this.template.querySelectorAll('[data-id="selectAllIndustry"]')[0].checked = false;
                length -= 1;
            }
        }
            
        handleIndustrySelectionChange(event)
        {
            if (this.selectedIndustryValues.indexOf(event.target.name) != -1) {
                for (var i = 0; i < this.selectedIndustryValues.length; i++) {
                var selected = this.template.querySelectorAll('[data-id="' + this.selectedIndustryValues[i] + '"]')[0];
                selected.value = event.target.value;
                   }
                }
        }



}  


  • handleSelectAllIndustryChk:- By clicking select all checkbox it will check all the checkboxes.
  • handleIndustryCheckbox:- Checks for checkboxes to see whether it is selected or
    
    unselected.
  • handleIndustrySelectionChange:- Used when value is selected from the picklist 
    
    and assigns that value to each and every selected picklist.

Apex Class:-

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> AccountList() {
        return [SELECT Id, Name ,Industry FROM Account LIMIT 5 ];
    }
}

OUTPUT:-




CONCLUSION
 
By using above mentioned javascript functions, We are able to set selected value of picklist field based for bulk/mass update records in lightning web component.

If you have any questions you can reach out our Salesforce Consulting team here.

Thursday, 20 May 2021

Lifecycle Hooks - Lightning Web Component

INTRODUCTION

A lifecycle hook is a JavaScript callback method which is called at a certain point in the lifecycle of a component instance. The components' lifetime was managed using the Aura system's init(), render(), rerender(), afterRender() and unrender() methods. In Lightning Web Component, callback methods are used to manage the components' lifespan, Lifecycle hooks are what they're called. You can adjust the actions by overriding these hooks. There are various life cycle hook methods to pick from, and we will go through each one in detail in this blog.

Here are the Types of lifecycle hooks

1. Constructor():

  • Whenever a component instance is created, this hook is invoked. 
  • The first statement must be super() with no parameters. 
  • Don’t use a return statement inside the constructor body.
  • This hook flows from parent to child, which means that it fires in the parent first. You can't access child elements because they don't exist yet. Properties aren't passed yet, either.
  • Properties are assigned to the component after construction and before the connectedCallback() hook.
  • The similarity of this hook in Aura is with init() event but init() Aura event flows from child to parent.


sample code

2. connectedCallback():

  • it fires when a component is inserted into the DOM. 
  • The connectedCallback() hook can be fired more than one time.
  • This hook flows from parent to child. You can’t access child elements because they don’t exist yet. 
  • Use connectedcallback() to interact with a component's environment. For example, you can utilize it for:
    • Establishing communication with the current document or container and coordinate behavior with the environment. 
    • Performing initialization tasks, such as fetch data, set up caches, or listen for events.
    • Subscribe and Unsubscribe from a Message Channel.


SAMPLE CODE

3. disconnectedCallback():

  • Invoked when the element is removed from a DOM. 
  • This hook flows from parent to child.
  • Use disconnectedCallback() to clean up work done in the connectedCallback(), like purging caches or removing event listeners.
  • You can also use this hook to unsubscribe from a message channel.

SAMPLE CODE

4. render():

  • To update UI, we can call this method. It may be called before or after connectedCallback().
  • It is rare for a portion to be referred to as render(). The most typical use is to apply correct template (HTML file) based on business logic. The method must return correct HTML template. 
  • For example, imagine that you have a component that needs to be rendered in two different ways but you don’t want to mix it in one HTML file. So, here we can create multiple HTML files in the component bundle. And then Import  them and add a condition in the render() method to return the correct template depending on the component's state.

SAMPLE CODE


FirstTemplate.HTML
SecondTemplate.HTML
App.HTML & App.js

5. renderedCallback():

  • it is called after rendering of every component. This lifecycle hook is specific to Lightning Web Components, it is not from the HTML custom elements specification. This hook flows from child to parent.
  • A component is rerendered when the value of property changes and that property is used either directly in a component template or indirectly in the getter of a property that is used in a template.
  • As this hook is called after every render of the component, we need to be careful if we perform some action in specific condition. It should be guarded with the condition that doesn't trigger an infinite rendering loop.


SAMPLE CODE

6. errorCallback(error,stack):

  • It captures the errors that may occur in the lifecycle hooks of all descendant components.
  • The error argument is a JavaScript native error object and stack parameter is a string.


SAMPLE CODE


summary


The framework manages the lifespan of Lightning web components. When the state of a component changes, the framework generates components, adds and removes them from the DOM, and renders DOM modifications. 

If you have any questions you can reach out our Salesforce Consulting team here.

Thursday, 4 March 2021

Lightning Web Component : Validate/Format currency field using lighting- input Attribute


INTRODUCTION/SCENARIO

While working on the Lightning Web Components for our most recent project, a Banking website for our client's business in Naples, Florida, USA. we came across a scenario where had to validate the input field accepting a value between 1 to 150,000 and formatted with leading $ sign. 

CHALLENGE

We implemented this functionality using LWC, but challenging part was formatting the input value with $ sign using an input element of HTML. 

APPROACH / SOLUTION 

We've used lightning-input instead of an HTML input element. The Lightning input field itself has attributes with validation as well as a format for currency. We only need to set attributes as per the requirement and, it would perform the desired action in the OOTB manner. 

A Lightning Web Component renders UI that must include an HTML file, a JavaScript file, and a metadata configuration file. 


Every UI component must have an HTML file with the root tag <template>.


myComponent.html


<template>
    <div class="slds-card">

        <!--show hide the form based on the validation-->
        <template if:true={showAmountInputBox}>

            <div class="slds-p-around_medium">
                <h2>Tell us what you need</h2>
                <lightning-input type="number" formatter="currency" step="1" 
                class="form-control is-invalid" onfocusout={checkAmountValue} value={inputAmount}
                label="How much would you like to borrow?">
                </lightning-input>
            </div>

        </template>

    <!-- Check on focusout of the box if amount is between $1 to $150000 -->
    <template if:true={greaterAmount}>
        <p class="slds-p-around_medium">Amount must not be greater than $150000. </p>
    </template>
    <template if:true={lesserAmount}>
        <p class="slds-p-around_medium">Amount must not be less than $1. </p>
    </template>
    </div>
</template>

myComponent.js


import { LightningElement,track } from 'lwc';

export default class myComponent extends LightningElement {

    @track inputAmount; // to store amount from input box
    @track greaterAmount=false; // check if amount is greater than $150000
    @track lesserAmount=false; // check if amount is less than $1
  
// handle onfocusout event to verify input amount

 checkAmountValue(event){
    const typedValue = event.target.value;
        
    if(typedValue !== undefined){
        event.target.value=typedValue;
    }

    this.inputAmount=typedValue;
    this.showPrevNext = false; 

    if(this.inputAmount>150000){ 
        this.greaterAmount=true; 
        this.lesserAmount=false; 
     } 
     else if(this.inputAmount<1){ 
        this.lesserAmount=true; 
        this.greaterAmount=false; 
    }
    else if(this.inputAmount === "" || this.inputAmount == null || this.inputAmount < 150000 || this.inputAmount >1){
        this.greaterAmount=false; 
        this.lesserAmount=false; 
   }
    
 }
    
}

myComponent.js-meta.xml



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

OUTPUT


SUMMARY

Hence, we have validation implemented with the formatting applied using the attributes of Lightning Input without any custom function OR JavaScript. 

If you have any questions you can reach out to our Salesforce Consulting team here.

Thursday, 25 February 2021

[Resolved]: Add Tooltip over a field section using visual force page in Object Page Layout.

Introduction/SCenario

There was a need of implementing tooltip on mouse hover for field section label on the object page layout for one of the our client - consulting firm based out of Atlanta, GA, USA.

We, all are familiar with showing tooltip on page layout by dragging & dropping the Lightning Component for a specific object field on the page layout, but displaying a tooltip on the Field Section label on the record/object page layout is quite challenging. So, in this blog, I will go through in detail how Tooltip can be displayed on the mouse hover for Field Section label on the object page layout.

APPROACH
To display the tooltip on the field section label, we need to utilize custom Visual Force page in the page layout. In that page, we can have customized HTML & CSS to show tooltip on the mouse hover.
PROCESS
I've developed a custom solution that involves creating a custom Visual Force Page called ToolTip. This Page contains the mechanism to display the Tooltip of  Account Name. The page needs to be customized using HTML and CSS to show the tooltip of an Account name on a Field Section Label.
ToolTip.vfp
After creating the visual force page, we need to drag & drop the page to the specific record page layout. As, I need to show tooltip of Account Name, I've used it on the account page layout.
OUTPUT
If you have any questions you can reach out our Salesforce Consulting team here.