Monday, 22 June 2020

LWC Cheat Sheet


Wire

JavaScript Find method -

var age = 17;
function myFunction() {
  document.getElementById("demo").innerHTML = ages.find(ageVal => {
   return ageVal >= age;
  });
}

Calling child LWC method from parent -

const child = this.template.querySelector('c-public-method-child');
console.log(JSON.stringify(child));
child.changeSelection(this.city);

Constructor should have super in LWC js -

constructor() {
 super();
 console.log('Parent > Constructor.');
}

Importing and rendering multiple templates in LWC js -

import template1 from './lifecycleChild.html';
import template2 from './template2.html';
render() {
 console.log('Child > render.');
 return this.showTemplate2 ? template2 : template2;
}

CustomEvent firing from child to the parent

//Firing the event from the child component 
var cusEvt = new CustomEvent('mychildevent',{detail:'I am the message from child to parent.',bubbles:true});
this.dispatchEvent(cusEvt);

//Approach1: Handling the event from parent UI -
[c-child onmychildevent={handleChildEvent}][/c-child]
Note: handleChildEvent is the method in parent
handleChildEvent(event) { console.log(event.detail); }

//Approach2: Handling the event from parent JS -
constructor() {
 super();
 console.log('constructor');
 this.template.addEventListener('mychildevent',this.handleChildEvent.bind(this));
}
Note: When addEventListener is used "bubble:true" should be there in CustomEvent

Pubsub: Application Event Handling -

Download pubsub repository.

Firing the event -

  import {fireEvent} from 'c/pubsub';
  import { CurrentPageReference } from 'lightning/navigation';

  @wire(CurrentPageReference) 
  pageRef;
  
  handleClick() {
   debugger;
   fireEvent(this.pageRef,'parent2event','I am the event firing from parent2 component.');
   //Note: Event Name should be all in small characters and should not have special characters
  }
 

Handling the event -

  import {registerListener,unregisterAllListeners} from 'c/pubsub';
  import { CurrentPageReference } from 'lightning/navigation';
  
  @wire(CurrentPageReference) 
  pageRef;
  
  connectedCallback() {
   console.log('connectedCallback');
   registerListener('parent2event',this.handleAppEvent,this);
  }
  disconnectedCallback() {
   console.log('disconnectedCallback');
   unregisterAllListeners(this);
  }
  handleAppEvent(payload) {
   console.log('***payload: '+payload);
  }
 

Reusable javaScript -

Utility.js -

  const add = function(num1,num2) {
   return num1 + num2;
  }
  const substract = function(num1,num2) {
   return num1 - num2;
  }
  const multiply = function(num1,num2) {
   return num1 * num2;
  }
  const divide = function(num1,num2) {
   return num1 / num2;
  }

  export {
   add,
   substract,
   multiply,
   divide
  }
 

calling reusable js functions -

  import {add,substract,multiply,divide} from 'c/utility';
  
  constructor() {
   super();
   console.log('add: ',add(200,100));
   console.log('sub: ',substract(200,100));
   console.log('mul: ',multiply(200,100));
   console.log(`Div: ${divide(200,100)}`);
  }
 

LDS to get and create records -

  import { LightningElement, track, wire } from 'lwc';
  import {createRecord,getRecord} from 'lightning/uiRecordApi'

  const fieldsArray = ['Contact.FirstName','Contact.LastName','Contact.Email','Contact.MobilePhone'];
  export default class ContactForm extends LightningElement {   

   @track recordId;

   @wire(getRecord,{recordId:"$recordId", fields: fieldsArray})
   contact;


   firstNameChangeHandler(event) {
    this.firstName = event.target.value;
   }
   lastNameChangeHandler(event) {
    this.lastName = event.target.value;
   }
   emailChangeHandler(event) {
    this.email = event.target.value;
   }
   mobileChangeHandler(event) {
    this.mobile = event.target.value;
   }
   
   createContact() {
    debugger;
    //Field API Names along with the data
    const fields = {
     "FirstName" : this.firstName,
     "LastName" : this.lastName,
     "Email" : this.email,
     "MobilePhone" : this.mobile
    };

    var recordInput = {
     apiName : "Contact", fields
    };
     
    //Using javaScript promise concept
    createRecord(recordInput).then(response => {
     console.log('Record Id: '+response.id);
     this.recordId = response.id;
    }).catch(error => {
     console.log('Error Object: '+JSON.stringify(error));
     console.log('Error Message: '+error.body.message);
    });

   }

   get retFirstName() {
    debugger;
    console.log('contact: '+JSON.stringify(this.contact));
    if(this.contact.data) {
     return this.contact.data.fields.FirstName.value;
    }
    return undefined;
   }

   get retLastName() {
    debugger;
    if(this.contact.data) {
     return this.contact.data.fields.LastName.value;
    }
    return undefined;
   }

   get retEmail() {
    debugger;
    if(this.contact.data) {
     return this.contact.data.fields.Email.value;
    }
    return undefined;
   }

   get retMobile() {
    debugger;
    if(this.contact.data) {
     return this.contact.data.fields.MobilePhone.value;
    }
    return undefined;
   }
   
   
  }
 

Imperative Apex Call, Toast Message and Navigation Service

Apex Class - Js - Template -

Wednesday, 25 December 2019

Lightning:Datatable Development from basic to advance

DatatableV4 with Lightning:Datatable by hard coding data - 
DatatableV4_1.cmp
DatatableV4_1Controller.js
DatatableV4 with Lightning:Datatable by querying the data from the database - 
DatatableV4Handler (Apex Class) -
DatatableV4_2.cmp -
DatatableV4_2Controller.js -

Friday, 6 September 2019

Lightning Datatable Component With Url Colums by forming the json from Apex Class Salesforce

Apex Classes -
    1. FieldInfoCls
    2. DatatableUrlCompCls

Lightning Component -
    1. LightningDatatableWithUrlColums_v2
-------
Apex Classes - ============== FieldInfoCls - DatatableUrlCompCls - Lightning Component - ===================== LightningDatatableWithUrlColums_v2 - ---------------------- LightningDatatableWithUrlColums_v2 Component - LightningDatatableWithUrlColums_v2 Controller -

Reason behind the above post. Problem -

 

Thursday, 5 September 2019

Lightning Web Components (Salesforce) - Key points


What is Web Stack?
    Collection of software applications needed for the Web Development can be called as Web Stack.
    It includes -
        * Operation System
        * Database
        * Business Logic
        * Web Server



What is ECMAScript?
    It is a javaScript standard. ECMAScript 7 is used as part of the Wab Stack 2019 standard.

What is rendering?
    The process of converting HTML tags to meaningful readable web page with the browser rendering engine.
   

What are the Standard Elements?
    The elements provided in HTML library. We can also create custom element as per the requirement which won't be part of standard HTML library.

What is event?
    When the page load completes or user perform mouse or keyboard operation events will trigger which can used to execute the javaScript.

What is Module?
    A module is a javaScript file.
    In a module we define variables and functions which can be exposed to other module by using "export" directive.
    To use the variables and functions of the other module we need to import other module by using "import" directive.
   
    The reason of using module is to decompose the logic. Instead of making all the functions available within the same file, if they maintain the functions in different files, based on the need we can import the corresponding module.



What is Directive?
    It is a token which is having specific behavior.
    Example: export, import
    It modifies the behavior of an existing element by assigning value and responding to change events.


What is Decorator?
    It is a function which is having predefined functionality.
    Syntax: @DecoratorName
    Similar to annotations in apex class.

What is Shadow DOM? 
    It is just a normal DOM except the separate behavior in relation to the rest of the page.It won't be having conflicts with the styles which applied to the rest of the page. It maintains in a separate DOM tree. (Alternative to iframe)
What are the Custom Elements?
Custom elements can be created to extend HTML and define our own tags.

What is template?
It is a reusable structure in the HTML page but it won't be rendered until we refer it in the javaScript.

What is Slot?
It is a place holder in template and the content can be replaced based on the need.

What are the Web Components?
It holds collection of web platform APIs and allows you to create custom functionality which can be used in Web Pages.

What are the Lightning Web Components?
Lightning Web Components uses core Web Components standards. Lightning web components are custom HTML elements built using HTML and modern JavaScript.

What is class in javaScript?
A class is a type of function, but instead of using the keyword function to initiate it, we use the keyword class, and the properties is assigned inside a constructor() method.

---------

Datatable Lightning Component with the row level actions salesforce

Apex Classes -
    1. LightningUtility
    2. DataTableServerContrl

Lightning Events -
    1. OppPopupCloseEvent
    2. PopupAppEvent
Lightning Tokens -
    1. defaultTokens
Lightning Component -
    1. RecordComp
    2. Datatable

Apex Classes - Lightning Events - Lightning Tokens - Lightning Component -

Live Demo -

Datatable with Row Level Actions Logic

Wednesday, 4 September 2019

Datatable with Export, Edit, Delete, new and export operations

Apex Classes -
    1. DatatableContrl
   
Lightning Events -
    1. InputFormCloseEvent
    2. SearchEvent
   
Lightning Components -
    1. Message.cmp
    2. SearchDatatable.cmp
    3. Pagination
    4. InputForm4MulRecs
    5. DatatableV2

Main Component -
    DatatableV2.cmp

Apex Classes - Lightning Events - Lightning Components -

Live Demo -

DatatableV2 Live Example

Missing Fields Request Creation Lightning Component which is using Record Edit Form and Custom Events Salesforce