Thursday, 22 August 2024

Lightning FrameWork

The Lightning Component framework is a UI framework for developing single page

applications for mobile and desktop devices


1) Aura Component Model

2) Lightning Web Component


Aura Vs LWC                                                    Shadow DOM


Too much Code to Write                                         Web Component


Rendering wasn't optional                                     Custom elements         


modern features was not available                             template  and slots

like modules, classes and promises


ES5 (2009)                                      ES62015 ES72016 ES82017 ES92018


Aura build on

this javascript

version


What is Lightning Web Component


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

It uses the core concepts of web Standards


Benefits


1. Lightweight framework

2. Better Performance

3. No need to learn different framework to developing application in salesforce

4. Interoperbility with lightning aura components

5. Better testing using jest

6. Better Security 


Component Naming Convention


 The folder and its files must follow these naming rules.

 

 . Must begin with a lowercase letter

 . Contain only alphanumaric or underscore characters

 . Must be unique in the namespace

 . Can't include whitespace

 . Can't end with an underscore

 . Can't contain two consective underscores

 . Can't contain a hyphen (dash)

 

 html

  helloWorld

 <template>

 </template>

 

 

 .xml

 

 <?xml version="1.0" encoding="UTF-8">

 <LightningComponentBundle xmlns="https://soap.sforce.com/2006/04/metadata">

 <apiVersion>49.0</apiVersion>

 <isExposed>false</isExposed>

 </LightningComponentBundle>

 

 Component Folder Structure

 

 Component

  helloWorld.html

  helloWorld.js

  helloWorld.js-meta.xml

  helloWorld.css

  helloWorld.svg

  moreSharedCode.js

  _test__/helloWorld.test.js

  

  

  

  Default files

  

  Files that should have same name as component and can have one file of same type in the

  component folder

  

  Any number of JS file you can add

  

  test file with same name as component with .test.js extension

  

  Naming Convention for LWC

  

  1. CamelCase : Each word in the middle of the respective phrase begins with a capital letter

  2. PascalCase : It is Same like Camel Case where first letter always in Capitalized 

  3. kebab-case : Respective phrase will be transferred to all lowercase with hyphen(-) separating 

     words

 

CaseName           camelCase          PascalCase               kebab-case

Exmple              helloWorld         HelloWorld              hello-world

usage               component Name     Component class Name    Component reference and Html attribute Name

 

Data Binding in a Template

Data binding in the Lightning web components is the Synchronization between the controller and 

the template(HTML)

                 My Full Name is {fullname}    Template(HTML)

 

fullname one way flow

from controller to Html 

js            fullname = "Salesforce"

Things to remember

1) In template we can access properly value directly if it's primitive  or object

2) Dot notation is used to access the property from an object 

3) LWC doesn't allow computed expressions like Name[2] 

    4) The property in {} must be valid javascript identifier or member expression.

     Like {name} or {user.name}

    5)  Avoid adding spaces around the property for example, {data}  

    

                                        

 

 

 



Thursday, 15 August 2024

Java Script Basic

  Spread Operator

the operator shap is three consective dots and is written as: 

Usages of sparead operator

1. Expanding String - Convert String into list of array

2. Combining Arrays - Combine array or add value to array

3. Combining Object - Combine Object or add value to Object

4. Create New Shallow Copy of Arrays and Object


sparead operator


1) Arrays


var arry = [a,b,c];

// array indax start from zero

console.log(arry[0]);

console.log(arry[1]);



//2 Object


var obj = {

"name" : "salesforce",

"age"  : "54",

}

console.log(obj.name)

console.log(obj.age)


// Spread Operator


//1. Expanding of string


let greeting = "Hello World"

let charlist = [...greeting]

console.log(charlist[10]);


//2.Combing array


let arr1 = ["amazon","persistent","google"];

let arr2 = ["feedback","instration"]


let arr3 = [...arr1, ...arr2];

console.log(arr3);



// 3.adding values to an array



let arr4 = ["a","b","c"];


let arr5 = [...arr4,"giri"];


console.log(arr5);


// 4. Combining Object


 let obj1 = {name:"salesforce", age:23, date:"23/10/1990}

 let obj2 = {name:"feedback", age:26}

 let obj3 = {...obj1, ...obj2}

 

 

 //5. Shallow copy

 

 var arr10 = ["x","y","z"]

 arr10.push(20)

 console.log(arr10)

 console.log(arr11)

 

 //6. Nasted copy

 

 var arrObj1 = [{name:"giri"},

                {name:"salesforce"}]

var arrobj1 = [...arrobj]


Destructring


The two most used data structure in javaScript are Object and Arrays


Destructring is a special syntax that allows us to "unpack" arrays or objects into a 

bunch of variables as sometimes that's more convenient


. Arrays destructing

. Object destructing 



// array destructing


let arr = ["amazon", "google"]


let [company1, company2] = arr


 console.log(company1)

 console.log(company2)

 

 // object destructing

 

  let options = {

                title:"zero to hero",

age  :23,

type : "CRM"}

let {title, age, type} = options

console.log(title)

console.log(age)

console.log(type)


String interpolation  


. string interpolation allows you to embed expressions in the string

. Template string use back-tick('') rather than the singe or double-quotes


var name = "salesforce troop";

console.log('Hello, ${name}!');



//string Interpolation with expressions


var a= 10;

var b = 20;


console.log('The sum of ${a} and ${b} is ${a+b}');


//string Interpolation


var name = "sales"

var name1 = "force"


console.log(name + name1);


var name = "Giri Kumar"

var age  = 35


var str = "my name is "+ name+"and my age is "+ age 


console.log(str)


var a = 2

var b = 3


var str1 = "the sum of"+a+ "and"+b+ "is" a+b

console.log(str1)


String Method


JavaScript provides many methods to play with strings. Below are some of the most commonly used string methods 

in LWC 


1.includes()

2.indexOf()

3.StartsWith()

4.Slice()

5.toLowerCase()

6.toUpperCase()

7.trim()


let str = "Hello guys i hope your are doing good"


//Include

//The includes() method determines whether a string contains

//the characters of specialfied string


let check = str.includes("hope")

console.log(check)


// indexof

// The indexof() method returns the posities of the first

// occurrence of a specified value in a string


let index = str.indexof("doing")

console.log(index)


//stratWith()

// determines whether a string begins with the characters

// of a specified string


console.log(str.startWith("Hello"))


//slice()

//method extracts parts of a string and returns the 

//extracted parts in a new string


  let newstr = str.slice(0, 5)

  console.log(newstr)

  

  //toLowerCase

  // converts string to lowercases letter

  

  let x = "my name is giri "

  console.log(x.toLowerCase())

  

  //trim() - remove whitespace from both sides of a string

    

  let searchtext = " salesforce lwc "

  console.log(searchtext.trim())

  

  let obj = {

            name: "Salesforce",

age : 23,

dob : '20/03/2024'

}

  console.log(Object.keys(obj))

  

  // Object.keys()

  

  console.log(object.keys(obj))

  

  // Object.values()

  

  console.log(object.values(obj))

  

  //JSON.stringify

   let str = JSON.stringify(obj))

  console.log(str)

  

  //JSON.parse

   console.log(JSON.parse(str))

  

  Arrays Method

  

  1) map() - loop over the array and return new array based on the value return.

  2) every() - return ture or false if every element in the array satisfy the condition.

  3) filter() - return new array with all the element that satisfy the condition

  4) some() - return true if at least one element in the array satisfy

  5) sort() - sort the element of an array

  6) reduce() -  this method reduces the array to asigle value(left to right)

  7) foreach() - this method calls for each array element

  

  let arr = [2,3,4,5,6,7,9,10]

  

 let newArray =  arr.map(funcation(currentItem, index, array){

   console.log('currentItem is ${currentItem},index ${index},array ${array}' )

   return currentItem*2

   })

  console.log(newArray)

  

  //filter()

  

   let filteredvalues = arr.filter(funcation(currentItem, index, array){

     return currentItem > 5

 })

   console.log(filteredvalues)

   

   //every

   let age = [32, 33, 18, 40]

   let agealladult = age.every(funcation(currentItem){

    return currentItem >=18

   })

   

   //some

   let agelist = [32, 33, 18, 40]

   let isadult = agelist.some(funcation(currentItem){

          return currentItem > 32

   })

    console.log(isadult)

//sort()

var names = ["giri","hari","john"]

console.log(names.sort())

//sorting of number

var points = [10,32,12,80,54]

points.sort(funcation(a,b){

 return a-b

})

console.log(sortedValue)

let num = [12, 78, 30]

let sum = num.reduce(funcation(total,currentItem){

  return total+currentItem

},0)

 console.log(sum)

 

 //for Each

 num.forEach(funcation(currentItem){

   console.log(currentItem)

 })

 Promise

 Promise is an object that may produce a single value sometime in the future

 promise are used to handle asynchronous operations in javaScript

 A Promise has three states

 1) pending

 2) fulfilled

 3) rejected

 Use Case from LWC point of view

 1. Fetching data from server 2) Loading file from system

 funcation checkIssuccess(data){

   return new Promise(funcation(resolve, reject){

   if(data === "success"){

    return resolve("successfully executed")

}else{

return resolve("unsuccessfully executed")

}

   })

  

}

checkIssuccess('success').then(funcation(result){

console.log(result)

}).catch(error){

console.log(error)

}

 

feach('https://api.github.com/user/karkranihil').then(function(){

  return return.json()

}).then(funcation(response){

console.log(response)

})

 

modules import and export

 

Exports

 

Exporting Use export keywords to export many variables or many method from a file 

 

export cont name = "giri"

 

  export function getname(){

   return "giri"

  }

 

Default export - use export defult keyword to export only one variable or a method from a file

 

Imports

 

Importing - Use import keyword to import variable or method from a given file path or modules

 

multiple imports

 

import {name,getname} from './filepath'

 

imports all exported members

 

  import * as utils from './filepath'

  

  import a module with a defult members

  

  import user from './filepath'

  

  

  utils

  

  export const PI = 3.14

  

  export funcation add(a,b){

   console.log(a+b)

  }

  //export {PI,add}

  

  export {PI_DATA as PI, add}

  

  export defult function minus(a,b){

   console.log(a-b)

  }

  

  script 

  

  import {PI, add} from '.utils';

  

  import * as UTILS from './utils'

  console.log(UTILS.PI)

  console.log(UTILS.add(2,3))

  console.log(UTILS.minus(8,5))

  

  

  QuerySelect

  ------------

  queryselector

  

  The queryselector() method returns the first element that matches a specified CSS

      selector(s) in the document


      queryselectorAll

      The queryselectorAll() method returns all element in the document that matches a specified CSS selector(s) as a static nodelist object

  example js

  document.querySelectorAll(selector)

  

   let element = document.queryselector('.abc')

   console.log(element.innerText)

   element.style.color="red"

   

   let elementAll = document.querySelectorAll('div')

   console.log(elementAll)

   Array.from(elementAll).foreach(funcation(item){

    return item.style.color="green"

   })

   

   example html

   <html>

    <head>

<title>  First HTML Page </title>

<head>

<body>

<div class="abc"> Hello Everyone </div>

<div> Hello LWC Developers </div>

<script type="module" src="./script.js"></script>

</body>

<html>

Event 

    An event is an action that occurs in the web browser, which the web browser

feedback to you so that you can response to it.

for example, when users click  a button on a webpage, you want to respond to this click

event by displaying a alert box.

Event handler - It is a block of code that will execute when the event occurs. It is also

known as an event listener

Two Common ways to add events

1. HTML Event Handler attribute - When we add event through HTML,Event always begins

  with on keyword like onclick,onchange,onkeyup

  

2. Event Listener - Event Handler provide two main method for dealing with the

  registering/deregistering event listener

. addEventListener() - register an event handler

. removeEventListener() - remove an event handler

 

<html>

  <head>

   <title>First HTML Page </title>

  </head>

  <body onclick="removeHandler()">Click</body>

   <div class="demo"></div>

   <script src = "./script.js"></script>

  </body>

</html>

  

//funcation firstFunction(){

// console.log("Hurray");  

//}

      

//let btn = document.querySelector("button")

// btn.addEventListener("click", firstFunction)

document.addEventListener("mousemovie", handler)

  

funcation handler(){

  document.querySelector(".demo").innerHTML = Math.random()  

}

  

     funcation removeHandler(){

  document.removeEventListener("mousemovie", handler)

}

   

    Event Propagation

Event Propagation explains the order in which events are received on the page from

the element where the event occurs and propagated through the DOM tree.

There are two main event modles

 

1. Event bubbling

2. Event Capturing

Event Bubbling

In the event bubbling model, an event starts at the most specific element and then 

flows upward toward the least specific element(the document or event window)

     

Element Button

Element div

Element body

Element html

Document

 

<html>

  <head>

    <title> First HTML Page </title>

  </head>

   <form onclick="alert('i am form')">

      I am form 

  <div onclick="alert('i am div')">

   <p onclick="alert('i am p')"> I am p </p>

  </div>

   </form>

</html>

  

   Custom Event

   

   In javaScript we can create our own custom event using CustomEvent

   Constructor

   

    Syntax

new customEvent("eventName",{options})

 

Example

                         ||                             Event name

             element.dispatchEvent( new customEvent ("hello",{

  detail : {name:"giri"} (detail property used to pass data)

  })),

  

  

     <html>

  <head>

   <title>First HTML Page  </title>

  </head>

  <body onclick="callcustommethod()">

   Click

  </body>

</html>

  

      js

  

   document.addEventListener("hello",funcation(data){

    console.log("hello has called and send" + data.detail)

   })

  

  funcation callcustommethod(){

   let event =  new customEvent("hello", {

detail: {"giri"}

})

document.dispatchEvent(event)

  }

  

Arrow Function

 

Arrow funcation allow us to write shorter funcation syntax

 

Example

 

funcation getName() {           ---> getName = () => {     --->  getName = () => "giri"

  return "giri"                          return "giri"

  }                                         }

  Normal funcation                Arrow funcation with return       Arrow funcation without return

  

  

  Benefits of Arrow functions

  

  Arrow syntax automatically binds this to the surrounding code's contex

  

<html>

<head>

<title> Arrow Function </title>

</head>

<body>

</body>

</html>

  

    // Arrow Function

funcation sum(data){

  let sum = data+10

  return sum

}

abc()

const sum  = data => {

let sum = data+10

return sum

}

console.log(sum(4,5))

 

const sum  = (data1, data2) => {

  let sum = data1+data2+10

  return sum

}

console.log(sum(4,5))

 

 var arr = [1,2,3,4]

 let newArr = arr.map(item)=>item*2)

 console.log(newArr)

 

 let obj = {

      name:"nikhil",

  getName:funcation(){

   console.log(this.name)

   funcation fullname(){

    console.log(this.name)

    console.log("my full name is" + this.name + "karan")

   }

    fullname()

  }

  }

  console.log(obj.getName())

  

  let obj = {

      name:"nikhil",

  getName:funcation(){

   console.log(this.name)// slip to the 

   cons  fullname =() => {

    console.log(this.name)

    console.log("my full name is" + this.name + "karan")

   }

    fullname()

  }

  }

  console.log(obj.getName())

  

  setTimeout

   The setTimeout() is  a method of the window object. The setTimeout() sets a timer

   and executes a callback function after the time expires 

   

   

   setInterval

   The setInterval() is a method of the window object. The setInterval() 

   repeatedly calls a function with a fixed delay between each call 

   

   

   .js

   

    let timeid = windows.setTimeout(function(){

console.log("hello")

},2000)

console.log(timeid)

 

// setInterval

 

let intervalId = window.setInterval(function(){

  console.log("hello")

}, 5000)

Tuesday, 26 December 2023

getPicklistValuesByRecordType Adaptor


getPicklistValuesByRecordType JS

import { LightningElement, wire } from 'lwc';

import {getPicklistValuesByRecordType, getObjectInfo} from 'lightning/uiObjectInfoApi'
import ACCOUNT_OBJECT from '@salesforce/schema/Account'
export default class GetPicklistValuesByRecordTypeDemo extends LightningElement {
    ratingOptions
    industryOptions
    selectedRating
    selectedIndustry
    @wire(getObjectInfo, {objectApiName:ACCOUNT_OBJECT})
    objectInfo

    @wire(getPicklistValuesByRecordType, {objectApiName:ACCOUNT_OBJECT, 
        recordTypeId:'$objectInfo.data.defaultRecordTypeId'})
        picklistHandler({data, error}){
            if(data){
                console.log(data)
                this.ratingOptions = this.picklistGenerator(data.picklistFieldValues.Rating)
                this.industryOptions = this.picklistGenerator(data.picklistFieldValues.Industry)
            }
            if(error){
                console.error(error)
            }
        }

    picklistGenerator(data){
        return data.values.map(item=>({"label":item.label, "value":item.value}))
    }

    handleChange(event){
        const {name, value} = event.target
        console.log(name +'==>' +value)
        if(name === 'industry'){
            this.selectedIndustry = value
        }
        if(name === 'rating'){
            this.selectedRating = value
        }
    }
}

getPicklistValuesByRecordType Html

<template>
<lightning-card  variant="Narrow"  title="Hello" icon-name="standard:account">
<div class="slds-var-p-around_medium">
    <template if:true={ratingOptions}>
    <lightning-combobox
        name="rating"
        label="Rating"
        value={SelectedRating}
        placeholder="Select Rating"
        options={ratingOptions}
        onchange={handleChange} ></lightning-combobox>
    </template>
    <template if:true={industryOptions}>
         <lightning-combobox
        name="industry"
        label="Industry"
        value={SelectedIndustry}
        placeholder="Select Industry"
        options={industryOptions}
        onchange={handleChange} ></lightning-combobox>
    </template>
</div>
</lightning-card>
</template>

Wednesday, 20 December 2023

LWC getPicklistValues

getPicklistValues

Use this wire adapter to get the picklist values for a specified field.

Syntax

import {lightningElement } from 'lwc';

import {getPicklistValues} from 'lightning/uiObjectInfoApi';

import  STATUS_Field from '@salesforce/schema/Account.status';

export default class Example LightningEvent{

@wire(getPicklistValues,{recordTypeId: '021XXXXXXXXXXXXX',fieldApiName:STATUS_Field})

propertyorfunction

}

Tuesday, 19 December 2023

LWC getObjectInfo adapter

Example 1  

getObjectInfoadapter js

import { LightningElement,track } from 'lwc';

import {getObjectInfoApi} from 'lightning/uiObjectInfoApi';

import Contact_OBJECT from '@salesforce/schema/Contact';

export default class AccountDisplatRecords extends LightningElement {

defaultRecordTypeId

@wire(getObjectInfoApi, {objectApiName:Contact_OBJECT})

objectInfo({data,error}){

if(data){

// check Inspect all the atribute we get it 

 this.defaultRecordTypeId = data.defaultRecordTypeId

}if(error){

  console.error(error)

}

}

}

getObjectInfoadapter html

<tempalte>

<lightning-card title = "getObjectInfo Adapter">

<div class="slds-var-p-around_medium">

 {defaultRecordTypeId}

</div>

</lightning-card>

</tempalte>

Another Example 2

getObjectInfoadapter js

import { LightningElement,track } from 'lwc';

import {getObjectInfoApi} from 'lightning/uiObjectInfoApi';

import Contact_OBJECT from '@salesforce/schema/Contact';

export default class AccountDisplatRecords extends LightningElement {

defaultRecordTypeId

@wire(getObjectInfoApi, {objectApiName:Contact_OBJECT})

objectInfo

}

getObjectInfoadapter html

<tempalte>

<lightning-card title = "getObjectInfo Adapter">

<div class="slds-var-p-around_medium">

 defaultRecordTypeId: {objectInfo.data.defaultRecordTypeId}

 defaultapiName: {objectInfo.data.apiName}

</div>

</lightning-card>

</tempalte>


 getObjectInfos


Use this wire adapter to get metadata for multiple objects. The response includes metadata describing

the fields, child relationships, record type, and theme for each objects


Syntax


import {LightningElement, wire} from 'lwc';

import {getObjectInfos} from 'lightning/uiObjectInfoApi';

import CONTACT_OBJECT from '@salesforce/schema/Contact';

import ACCOUNT_OBJECT from '@salesforce/schema/Account';

export default class GetObjectInfosExample extends LightningElement{

objectapirecords = [ACCOUNT_OBJECT,CONTACT_OBJECT];

@wire(getObjectInfos,{objectApiNames : $objectapirecords})

propertyorFunction

}

Parent to Child Passing Data Use @wire

Parent to Child Passing Data Value 

public class DisplayAccountRecordsget{

public static list<contact> getAccountRecords(){

return [select id,lastname,firstname,phone from contact limit 10];

}

}

parenttochildpassdata js

-----------------------------

import {LightningElement} from 'lwc';

import getrecords from '@salesforce/apex/DisplayContactRecordsget.getContactRecords';

export default class parenttochildpassdata extends LightningElement {

datadisplayed

@wire(getrecords)

datawire({data,error})

if(data){

this.datadisplayed = data;

} else if(error){

 console.log('Error feacting data from Apex:'+error);

}

parenttochidpassdata html

<template>

<lightning-card>

<c-childtoparentpassdata contacts = {datadisplayed}><c-childtoparentpassdata>

</lightning-card>

</template>

childtoparentpassdata js

import {lightningElement , api} from 'lwc';

export default class childtoparentpassdata extends LightningElement {

@api contacts

}

childtoparentpassdata html

<template>

<lightning-card variant="Narrow"  title="Parent to Child" icon-name="standard:contact">

<template if:true={contacts}>

<template for:each={contacts} for:item = "conlist">

<li key={conlist.id}> Contact FirstName - {con.FirstName}

                      Contact LastName -  {con.LastName} 

                      Contact Phone - {con.Phone}</li>

</template>

</lightning-card>

</template>

Child To Parent Data Passing Value

Chtil to Parent Passing Data Apex 

public class DisplayAccountRecords{

public static list<account> getAccountRecords(){

return [select id,name,phone from account];

}

}

Childaccountinsertrecord  Js Component Name

import { LightningElement  } from 'lwc';

import getrecords from '@salesforce/apex/DisplayRecords.getAccountRecords';

export default class ChildaccountinsertComponent extends LightningElement {

@wire(getrecords)

wirdata({data,error}){

if(data){

 const childcomponentdata = new CustomEvent('dataready',{detail:data});

  this.dispatchEvent(childcomponentdata);

} else if(error){

console.log('Error feacting data from Apex:'+error);

}

}

}

Childaccountinsertrecord  Js Component Name

import { LightningElement  } from 'lwc';

import getrecords from '@salesforce/apex/DisplayRecords.getdisplayedrecords';

export default class ChildaccountinsertComponent extends LightningElement {

@wire(getrecords)

wirdata({data,error}){

if(data){

 const childcomponentdata = new CustomEvent('dataready',{detail:data});

  this.dispatchEvent(childcomponentdata);

} else if(error){

console.log('Error feacting data from Apex:'+error);

}

}

}

childaccountinsertrecord  html Component Name

<template>

<!- I can not   displayed  any data ->

</template>

Parentaccountinsertrecord Js Component Name

import { LightningElement  } from 'lwc';

export default class ParentaccountinsertComponent extends LightningElement {

receivedData

handleDataReady(event){

this.receivedData = event.detail

}

}

Parentaccountinsertrecord html Component Name

<template>

<lightning-card  title= "Parent Comonent">

<div>

<c-childaccountinsertrecord  ondataready = {handleDataReady}></c-childaccountinsertrecord>

</div>

<template if:true={receivedData}>

<template for:each={receivedData} for:item={acc}>

  <li> Account ID :- {acc.id} </li>

  <li> Account Name :- {acc.Name} </li>

  <li> Account Phone :- {acc.Phone} </li>

</template>

</lightning-card>

</template>