Play Games

Search This Blog

Wednesday, February 2, 2022

How to filter a list based on some conditions in javascript file of Lightning web component - Salesforce Globe For You

How to filter a list based on some conditions in javascript file of Lightning web component - Salesforce Globe For You

Problem: For example I have a variable which holds list of Lead records fetched from backend apex method.Now I need to create a new variable 

which will hold only Leads whose LeadSource is Web.

Solution: Repeat the existing list using for each loop and then add each element to new list only if that specific condition met.

Example:

Apex Class: LeadController

public class LeadController {

    @AuraEnabled(cacheable=true)

    public static List<Lead> getLeads() {

        List<Lead> lstLead = new List<Lead>();

        lstLead = [Select id,name,leadSource from Lead order by Createddate Limit 3];

        return lstLead;

    }

}

filterRecordsInLWC.html:

<template>  

    <lightning-card title="Iteration of Lead Records In LWC">  

      <div class="slds-p-around_small">  

        <template for:each={lstLead} for:item="objLead" for:index="index">  

          <div class="slds-p-left_small" key={objLead.Id}>  

            Name: {objLead.Name}  Lead Source :{objLead.LeadSource}  

          </div>  

        </template>  

      </div>  

    </lightning-card><br/>

    <lightning-card title="Filtering of Lead Records In LWC">  

        <div class="slds-p-around_small">  

          <template for:each={lstFilteredLead} for:item="objLead" for:index="index">  

            <div class="slds-p-left_small" key={objLead.Id}>  

              Name: {objLead.Name}  Lead Source: {objLead.LeadSource} 

            </div>   

          </template>  

        </div>  

    </lightning-card>  

</template>

filterRecordsInLWC.js:

import { LightningElement, wire ,track} from 'lwc';

import getLeads from '@salesforce/apex/LeadController.getLeads';

export default class FilterRecordsInLWC extends LightningElement {

    @track lstLead;

    @track lstFilteredLead = [];

    @wire(getLeads) wiredLeads(result,error){

        if(result.data){

            this.lstLead  = result.data;

            for(let i=0; i<this.lstLead.length; i++){

                if(this.lstLead[i].LeadSource == 'Web') {

                    this.lstFilteredLead.push(this.lstLead[i]);

                }

            }

            

        } else {

            console.log(error);

        }

    }

}

filterRecordsInLWC.js-meta.xml:

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

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

    <apiVersion>51.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__RecordPage</target>

        <target>lightning__AppPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

Output:



No comments:

Post a Comment