Wednesday, January 4, 2023

Date Validation in LWC

 



dateValidation.html

 <template>

<lightning-card title="Date Validation in LWC">
<div class="slds-p-around_medium">
<lightning-input type="date" name="startDate" label="Start Date"
onchange={dateHandler}></lightning-input>
<lightning-input type="date" name="endDate" label="End Date"
onchange={dateHandler}></lightning-input>
<template if:true={error}>
<p class="slds-text-color_error">{error}</p>
</template>
<lightning-button variant="brand" label="submit" onclick={submitHandler}
class="slds-m-top_medium"></lightning-button>
</div>
</lightning-card>

</template>  


dateValidation.js

import { LightningElement } from 'lwc';

export default class DateValidation extends LightningElement {
startDate
endDate
error
dateHandler(event){
const {name, value} = event.target
this[name] = value
}

submitHandler(){
if(this.validateDate(this.startDate, this.endDate)){
console.log("Date is Valid")
} else{
this.error = "Invalid Input...End Date cannot be greater than Start Date"
}
}

validateDate(startDate, endDate){
return new Date(startDate).getTime() < new Date(endDate).getTime()
}
}

Generate CSV in LWC

 


CsvController.cls

public with sharing class CsvController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts(){
return [SELECT Id, Name, Phone, AnnualRevenue, Industry from Account];
}
}


csvDemo.html
<template>
<lightning-card title="CSV Demo">
<div class="slds-p-around_medium">
<template if:true={accountData}>
<template for:each={accountData} for:item="account">
<p key={account.Id}>{account.Name}</p>
</template>
</template>
<lightning-button label="Generate CSV" onclick={csvGenerator}
variant="brand"></lightning-button>
</div>
</lightning-card>
</template>

csvDemo.js
import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/CsvController.getAccounts'
import {exportCSVFile} from 'c/utils'
export default class CsvDemo extends LightningElement {
accountData
accountHeaders={
Id:"Record Id",
Name:"Name",
AnnualRevenue:"Annual Revenue",
Industry:"Industry",
Phone:"Phone"
}
@wire(getAccounts)
accountHandler({data, error}){
if(data){
console.log(data)
this.accountData = data
}
if(error){
console.error(error)
}
}

csvGenerator(){
//headers, totalData, fileTitle
exportCSVFile(this.accountHeaders, this.accountData, "account_records")
}
}


utils.js

  export function exportCSVFile(headers, totalData, fileTitle){

if(!totalData || !totalData.length){
return null
}
const jsonObject = JSON.stringify(totalData)
const result = convertToCSV(jsonObject, headers)
if(!result){
return null
}
const blob = new Blob([result])
const exportedFileName = fileTitle? fileTitle+'.csv':'export.csv'
if(navigator.msSaveBlob){
navigator.msSaveBlob(blob, exportedFileName)
} else if (navigator.userAgent.match(/iPhone|iPad|iPod/i)){
const link = window.document.createElement('a')
link.href='data:text/csv;charset=utf-8,' + encodeURI(result);
link.target = "_blank"
link.download=exportedFileName
link.click()
} else {
const link = window.document.createElement('a')
if(link.download !== undefined){
const url = URL.createObjectURL(blob)
link.setAttribute("href", url)
link.setAttribute("download", exportedFileName)
link.style.visibility='hidden'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
}
}

function convertToCSV(objArray, headers){
const columnDelimiter = ','
const lineDelimiter = '\r\n'
const actualHeaderKey = Object.keys(headers)
const headerToShow = Object.values(headers)
let str = ''
str+=headerToShow.join(columnDelimiter)
str+=lineDelimiter
const data = typeof objArray !=='object' ? JSON.parse(objArray):objArray
data.forEach(obj=>{
let line =''
actualHeaderKey.forEach(key=>{
if(line !=''){
line+=columnDelimiter
}
let strItem = obj[key] ? obj[key]+'': ''
line+=strItem? strItem.replace(/,/g, ''):strItem
})
str+=line+lineDelimiter
})
return str
}

Remove or Add Class on Button Click in LWC

 


removeOrAddClass.html
<template>
<div class="slds-hide slds-text-heading_small">Hello!!!!</div>
<lightning-button label="Show Div" onclick={handleClass}> </lightning-button>
</template>

removeOrAddClass.js

import { LightningElement } from 'lwc';

export default class RemoveOrAddClass extends LightningElement {
handleClass(){
const elmnt = this.template.querySelector('.slds-text-heading_small')
if(elmnt){
elmnt.classList.remove('slds-hide')
elmnt.classList.add('slds-text-color_error')
}
}
}

Tuesday, January 3, 2023

Use Lightning Design System Design Tokens in LWC

 

Design tokens are named entities that store visual design attributes, such as margins and spacing values, font sizes and families, or hex values for colors.

Use CSS variables in a Lightning web component to access Lightning Design System design tokens. Lightning web components can use any Lightning Design System design token marked Global Access.

designTokenInLWC.html

 <template>

<div>Design Token in LWC</div>

</template>

designTokenInLWC.js

import { LightningElement } from 'lwc';

export default class DesignTokenInLWC extends LightningElement {}

To reference a design token in your Lightning web component’s CSS, use the --lwc- prefix and reference the token name in camelCase
/* myWebComponent.css */
div {
    margin-right: var(--lwc-spacingSmall);
}

designTokenInLWC.css

  div{

color:var(--lwc-brandAccessible);

background:var(--lwc-colorBackgroundAlt);
}


Dynamic CSS in LWC

 



dynamicCss.html

  <template>

<lightning-card title="Dynamic CSS">
<div class="slds-var-m-around_medium">
<lightning-input type="number" value={currentVal} label="Percentage"
onkeyup={changeHandler}></lightning-input>
<div style={show} class="slds-notify slds-notify_alert
slds-theme_alert-texture slds-theme_error" role="alert">
Hey!!!
</div>
</div>
</lightning-card>

</template>

dynamicCss.js

import { LightningElement } from 'lwc';

export default class DynamicCss extends LightningElement {
currentVal = 10;
changeHandler(event){
this.currentVal = event.target.value;
}
get show(){
return `width:${this.currentVal}%`;
}
}

Styling Across Shadow DOM in LWC

 


shadowDomStyling.html

 <template>

<lightning-card title="CSS across Shadow DOM">
<div class="slds-var-m-around_medium">
<lightning-button label="testing" title="testing"></lightning-button>
</div>
</lightning-card>

</template>

shadowDomStyling.js

import { LightningElement } from 'lwc';

export default class ShadowDomStyling extends LightningElement {
isLoaded = false;
renderedCallback(){
if(this.isLoaded) return
const style = document.createElement('style')
style.innerText = `c-shadow-dom-styling .slds-button{
background: red;
color: white;
} `;
this.template.querySelector('lightning-button').appendChild(style);
this.isLoaded = true;
}
}