Showing posts with label lighting web components. Show all posts
Showing posts with label lighting web components. Show all posts

Tuesday, January 3, 2023

Dynamic popup/modal using Lightning-modal in Lightning Web Components(LWC)

This post explains how to open the popup using Lightning web components (LWC).

  • Created the lwcmodal component this component has the lighting modal base components to open the popup/modal.
  • import LightningModal from lightning/modal. The component has access to the normal LWC resources as well as the special container, helper components, methods, and events of the lightning/modal module.

LWCModal Component

lwcmodal.html

<template>
	<lightning-modal-header label={label}></lightning-modal-header>
	<lightning-modal-body>
		<lightning-datatable key-field="id" data={conData} columns={columns}>
		</lightning-datatable>
	</lightning-modal-body>
	<lightning-modal-footer>
		<lightning-button variant="brand" label="OK" onclick={handleOkay}></lightning-button>
	</lightning-modal-footer>
</template>

lwcmodal.js

import { api } from 'lwc';
import LightningModal from 'lightning/modal';

export default class Lwcmodal extends LightningModal {
    @api conData;
    @api columns;
    @api label;

    handleOkay(event) {
        this.close('okay');
    }
}

  • LightningModal provides a .open() method which opens a modal and returns a promise that asynchronously resolves with the result of the user’s interaction with the modal.
  • Use this.close(result) to close the modal, where the result is anything you want to return from the modal. The .close() operation is asynchronous to display a brief fade-out animation before the modal is destroyed. The result data can’t be modified after the close operation begins.
The .open() method lets you assign values to the modal's properties. LightningModal provides these properties.

label - Required. Sets the modal's title and assistive device label. If the modal has a header, set the label in the lightning-modal-header component. If the modal doesn't have a header, set the label property when opening the modal.

size - Determines how much of the viewport width the modal uses. Supported values are small, medium, and large, which you can set when you open the modal. The default value is medium. The length of the modal is determined by the amount of content.

description - Sets the modal's accessible description. It uses the aria-description attribute where supported, or falls back to aria-describedby. If you set a custom description value, include the label name at the beginning of your description, because some screen readers only read the description and not the label.

disableClose - Prevents closing the modal by normal means like the ESC key, the close button, or .close(). For example, you could briefly set disableClose to true while a completed form is saving, so the user doesn't dismiss the modal early.

dynamicmodal.html
<template>
    <lightning-card  variant="Narrow">
        <p class="slds-p-horizontal_small">When clicking the button it opens the dynamic modal.<br/>
            <lightning-button variant="brand" onclick={handleContactData} label="Show Contact Data"></lightning-button>
        </p>
    </lightning-card>
</template>
dynamicmodal.js
import { LightningElement } from 'lwc';
import MyModal from "c/lwcmodal";
import getContacts from '@salesforce/apex/LWCExampleController.getContacts';

export default class Dynamicmodal extends LightningElement {
    consData;

    columns = [
        { label: 'First Name', fieldName: 'FirstName', type:'text' },
        { label: 'Last Name', fieldName: 'LastName', type: 'text' },
        { label: 'Name', fieldName: 'Name', type: 'text' },
        { label: 'Email', fieldName: 'Email', type: 'email' },
    ];
    connectedCallback() {
        getContacts().then(res => {
            console.log('res => ', res);
            this.consData = res;
        })
            .catch(error => {
                console.log('error => ', error);
            });
    }

    async handleContactData() {
        const result = await MyModal.open({
            label: 'Contact Data',
            size: 'large',
            columns: [...this.columns],
            conData : [...this.consData]
        });
        // if modal closed with X button, promise returns result = 'undefined'
        // if modal closed with OK button, promise returns result = 'okay'
        console.log('result ==> ',result);
    }
}
Apex class
public inherited sharing class LWCExampleController {

    @AuraEnabled(Cacheable = true)
    public static List<Contact> getContacts() {
        return [SELECT Id, Name, FirstName, LastName, Email 
                FROM Contact 
                WHERE Email != null 
                ORDER BY CreatedDate DESC NULLS LAST limit 10];
    }
}
Example




Tuesday, June 23, 2020

How to check Lightning Web Component(lwc) Is Connected to the DOM?

we have already connectedCallback() and disconnectedCallback() lifecycle hooks to react when a component is connected to and disconnected from the DOM. However, using the Node.isConnected property is more ergonomic developer experience.

The Node.isConnected property, which returns a Boolean indicating whether the component is connected to the DOM. Simply use this.isConnected in a component’s JavaScript.

import { LightningElement } from 'lwc';
export default class MyComponent extends LightningElement {
    someMethod() {
        const cmp = this;
        const aPromise = new Promise(tetherFunction);
        aPromise.then((result) => {
           if (cmp.isConnected) {
               // Update the component with the result.
           } else {
               // Ignore the result and maybe log.
           }
        })
    }
}

Wednesday, March 13, 2019

dual list box component in Lightning Web Components(lwc)

This post explains how to create a dual list box in lightning web components(lwc)

Demo
dualListBoxLWCDemo.html
<template>
    <lightning-card title="Dual List Box Example" icon-name="custom:custom43">
        <template if:true={IndustryValues.data}>
            <lightning-dual-listbox name="Industries"
                                    label="Select Industries"
                                    source-label="Available"
                                    selected-label="Selected"
                                    field-level-help="This is a dual listbox"
                                    options={IndustryValues.data.values}
                                    onchange={handleChange}></lightning-dual-listbox>
        </template><br/>
    <div class="slds-box" >
        <p>Selected values are: <b style="color:blue;">{selected}</b></p>
    </div>
</lightning-card>
</template>

dualListBoxLWCDemo.js
import {LightningElement, track, wire} from 'lwc';
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 DualListBoxLWCDemo extends LightningElement {
    @track _selected = []; // this array tracks the seleted values

    // Getting Account Object info using wire service
    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    objectInfo;

    // Getting Pickvalues based on default recordtype using wire service
    @wire(getPicklistValues, { recordTypeId: '$objectInfo.data.defaultRecordTypeId', fieldApiName: INDUSTRY_FIELD})
    IndustryValues;

    // assigning none if you are not seleted any values
    get selected() {
        return this._selected.length ? this._selected : 'none';
    }

    // Handling the change event
    handleChange(event) {
        this._selected = event.detail.value;
    }
}

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

Result