Lightning Web Component Combobox

Let us discuss here how to use the Lightning Web Component Combobox .lightning-combobox is an input element that enables single selection from a list of options. The result of the selection is displayed as the value of the input. In this example, we will be showing the list of the opportunities based on the selected stage name. Refer this link to environment setup 

1.Create an apex class 

create an Apex class that will be fetching the opportunities based on the selected stage name . it this class we have an Aura Enabled method that will accept the stage name and return the list of opportunities. Use this SFDX command to create an apex class

sfdx force:apex:class:create -n OpportunityByStage -d force-app/main/default/apex

Here is the complete apex class

public with sharing class OpportunityByStage {

   @AuraEnabled(cacheable=true)
    public static List<Opportunity> getOppByStage(String stage) {
        System.debug('Stage Name'+stage);
        return [SELECT Id, Name ,StageName, CloseDate, Account.Name from Opportunity where StageName = :stage];
    }

}

 

2. Create a Lightning Web Component 

Now create a lightning web component that will display the combobox which contains the opportunity stage names .based on the selected opportunity stage name this component will display the list of opportunities.

Use this SFDX command to create a lightning web component

sfdx force:lightning:component:create --type lwc -n ComboboxEx -d force-app/main/default/lwc

Here is the ComboboxEx.html code

<template>
    <h6> Get Opportunities based on the Selected Opportunity Stage </h6>
    <lightning-combobox name="Opportunity Stage" label="Opportunity Stage" placeholder="Choose Status" value={value}
        onchange={handleChange} options={statusOptions}>
    </lightning-combobox>
    <template if:true={opportunities}>

        <table class="slds-table">
            <thead>
                <tr class="slds-line-height_reset">
                    <th class="slds-text-title_caps" scope="col">
                        <div class="slds-truncate">Opportunity Name</div>
                    </th>
                    <th class="slds-text-title_caps" scope="col">
                        <div class="slds-truncate">Stage</div>
                    </th>
                    <th class="slds-text-title_caps" scope="col">
                        <div class="slds-truncate">Close Date</div>
                    </th>
                </tr>
            </thead>
            <tbody>
                <template for:each={opportunities} for:item="opp">
                    <tr class="slds-hint-parent" key={opp.Id}>
                        <td>
                            <div class="slds-truncate" key={opp.Id}>{opp.Name}</div>
                        </td>
                        <td>
                            <div class="slds-truncate" key={opp.Id}>{opp.StageName}</div>
                        </td>
                        <td>
                            <div class="slds-truncate" key={opp.Id}>{opp.CloseDate}</div>
                        </td>
                    </tr>
                </template>


            </tbody>
        </table>
    </template>

</template>

Here is the ComboboxEx.js JavaScript controller.

import {
    LightningElement,
    api,
    wire,
    track
} from 'lwc';
import getOppByStage from '@salesforce/apex/OpportunityByStage.getOppByStage';

export default class ComboboxEx extends LightningElement {
    @track opportunities;
    @track error;
    @track
    statusOptions = [{
            value: 'Prospecting',
            label: 'Prospecting'
        },
        {
            value: 'Qualification',
            label: 'Qualification'
        },
        {
            value: 'Needs Analysis',
            label: 'Needs Analysis'
        },
        {
            value: 'Closed Lost',
            label: 'Closed Lost'
        },
        {
            value: 'Closed Won',
            label: 'Closed Won'
        }
    ];
    @track value = 'Prospecting';
    handleChange(event) {
      const select = event.detail.value;
        getOppByStage({
                stage: select
            })
            .then(result => {
                this.opportunities = result;
                this.error = undefined;
            })
            .catch(error => {
                this.error = error;
                this.opportunities = undefined;
            });

    }
}

Here is the ComboboxEx.js-meta.xml configuration file

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>

</LightningComponentBundle>

 

3. Push Changes and add the Component to record page 

Now push the changes using this SFDX command

sfdx force:source:push

Now add this web component to the opportunity record page using lightning app builder and you can able to see the result as shown below.

Now select the stage name from the combobox and it will display the list of opportunities as shown below.

Lightning Web Component Accordion

Let us discuss here how to create an Accordion using the Lightning Web Component lightning-accordioncomponent. A lightning-accordion component groups related content in a single container. Only one accordion section is expanded at a time. When you select a section, it’s expanded or collapsed. Each section can hold one or more Lightning components. To create Lightning web component we need to SFDX. Please refer this link for Environment setup for development. 

1.Create an apex class 

Now create an apex class to get the data from the Salesforce. here we will be fetching the accounts and its contacts data and will be displaying them like an accordion.

use this SFDX command to create an apex class

sfdx force:apex:class:create -n GetAccountContactData -d force-app/main/default/apex

Here is the complete code

public with sharing class GetAccountContactData {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountData() {
        return [SELECT Id, Name ,(Select Id ,Name from Contacts) from Account];
    }
}

 

2. Create a Lightning Web Component 

Create a lightning web component that will show the accordion. run the following SFDX command to create a lightning web component.

sfdx force:lightning:component:create --type lwc -n AccordionEx -d force-app/main/default/lwc

Here is the code for the AccordionEx web component.

Here is the AccordionEx.html code that will display the Accordion.

<template>
    <h6>Accoridan Exmape v8</h6>

    <lightning-accordion allow-multiple-sections-open={multiple}>
        <template if:true={accounts}>
            <template for:each={accounts} for:item="acc">
                <lightning-accordion-section name={acc.Name} label={acc.Name} key={acc.Id}>
                    <template for:each={acc.Contacts} for:item="con">
                        <lightning-accordion-section name={con.Name} label={con.Name} key={con.Id}>
                            {con.Name}
                        </lightning-accordion-section>
                    </template>

                </lightning-accordion-section>
            </template>
        </template>
    </lightning-accordion>
</template>

Here is the AccordionEx.js JavaScript controller class.

import {LightningElement,api,wire,track} from 'lwc';
import getAccountData from '@salesforce/apex/GetAccountContactData.getAccountData';

export default class AccordionEx extends LightningElement {
@track multiple = true;
@track accounts ;
@wire(getAccountData) 
wiredAccountss({
    error,
    data
}) {
    if (data) {
        this.accounts = data;
        console.log(data);
        console.log(JSON.stringify(data, null, '\t'));
        
        data.forEach(function (item, key) {
            console.log(key); 
            console.log(item); 
        });
        
    } else if (error) {
        this.error = error;
    }
}

}

Here is the AccordionEx.js-meta.xml configuration file which allows us to add this component to the record page.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>

</LightningComponentBundle>

3.Push changes

Now push the changes to scratch org using this below SFDX command

sfdx force:source:push

Now after pushing the changes to add this lightning web component to the record page. Go to the lightning app builder and add this component to the record page and save it .which will be displayed similar accordion on the record page.

 

 

 

 

 

Passing Current Object Name to Lightning Web Component

Lets us discuss here how to pass the current object name to the lightning web component. If a component is used on a Lightning record page, you can pass the component the API name of the current object. In the component’s JavaScript class, use the @api decorator to create a public objectApiName property. When your component is invoked in a record context in Lightning Experience or in the mobile app, the objectApiName is set to the API name of the object associated with the record being viewed, for example: Account. The objectApiName is set only when you place or invoke the component in an explicit record context. In all other cases, the objectApiName isn’t set, and your component shouldn’t depend on it.

 Create a lightning component

Create a new lightning web component using the below SFDX command.
sfdx force:lightning:component:create --type lwc -n ViewObject -d force-app/main/default/lwc

Here is the ViewObject.html markup code

<template>
<lightning-record-form record-id={recordId} object-api-name={objectApiName} layout-type="Full" mode="view">
    </lightning-record-form>
</template>

Here is the JavaScript controller class code .In the component’s JavaScript class, use the @api decorator to create a public objectApiName property and recordId property.

import { LightningElement ,api} from 'lwc';

export default class ViewObject extends LightningElement {
    @api objectApiName;
    @api recordId;

}

Here is the ViewObject.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>

</LightningComponentBundle>

Push the changes

Now push the changes to scratch org using the below SFDX command

sfdx force:source:push

Add this component to record page and you can able to see the output as shown below

Get Record Id into Lightning Web Components

Let us discuss here how to get the current record id into the lightning web components.  If a component is used on a Lightning record page, you can pass the component the ID of the current record. In the component’s JavaScript class, use the @api decorator to create a public recordId property.

In this example, we will be using the lightning-record-view-form to show the record data. Let’s start with the simple lightning web component and then we will see another example of how to pass the record id to the apex controller from the lightning web component.

 Create a Lightning web component

Now create a lightning web component using the following SFDX command

sfdx force:lightning:component:create --type lwc -n RecordIdExample -d force-app/main/default/lwc

Here is the RecordIdExample.html code and in this code, we are using the lightning-record-view-form to show the account data.

<template>
    <div class="boarder">
        <lightning-record-view-form record-id={recordId} object-api-name="Account">
            <div class="slds-grid">
                <div class="slds-col slds-size_1-of-2">
                    <lightning-output-field field-name="Name"></lightning-output-field>
                    <lightning-output-field field-name="Phone"></lightning-output-field>
                </div>
                <div class="slds-col slds-size_1-of-2">
                    <lightning-output-field field-name="Industry"></lightning-output-field>
                    <lightning-output-field field-name="AnnualRevenue"></lightning-output-field>
                </div>
            </div>
        </lightning-record-view-form>
    </div>
</template>

Here is the RecordIdExample.js controller. In this JavaScript class, use the @api decorator to create a public recordId property.

import { LightningElement,api } from 'lwc';

export default class RecordIdExample extends LightningElement {
     @api recordId;
}

Sample RecordIdExample.css

.boarder {
    background: blue !important;
    background-color: royalblue !important;
    border: 10px solid blueviolet !important;
}

Here is the RecordIdExample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>

</LightningComponentBundle>

Push Changes to Scratch Org 

Now push the changes from the local development to scratch org using this command

sfdx force:source:push

Add the lightning web component to the account record page using app builder and you can able to see the result as shown below.

 

 

Update code to pass record Id to Apex controller 

Let us make some changes now to the component. Now we will update the code in such a way that will get show the data for the selected account. Let us understand how to pass the record id to the apex controller here. create an apex class using this SFDX command

sfdx force:apex:class:create -n ContactData -d force-app/main/default/apex

Here is the ContactData apex class.

public with sharing class ContactData {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContacts(String accId) {
        return [SELECT Id, Name ,Email, Phone, Account.Name from Contact where AccountId = :accId];
    }
}

Now update the RecordIdExample.html markup code as shown below

<template>
    <div class="boarder">
        <template if:true={contacts.data}>
            <ui>
                <template for:each={contacts.data} for:item="contact">
                    <li key={contact.Id}>{contact.Name}</li>
                </template>
            </ui>
        </template>
    </div>
</template>

Now update the RecordIdExample.js controller as shown below. Now in this JavaScript controller, we are passing the current record id to apex controller and will get the data.

import { LightningElement,api,wire,track } from 'lwc';
import getContacts from '@salesforce/apex/ContactData.getContacts';

export default class RecordIdExample extends LightningElement {
     @api recordId;
    @wire(getContacts, {accId:'$recordId' })
      contacts;
}

If you add the above component to the account record page, you can able to see the list of contacts related to the account as shown below.