Concepts or coding lessons of Salesforce that you can implement easily

Showing posts with label LWC. Show all posts
Showing posts with label LWC. Show all posts

Create Custom Lookup in LWC in Simple way

 In this blog we are going to see how to create Custom lookup in LWC.


1. Create CustomLookupControllerLWC apex class and copy paste below code

public with sharing class CustomLookupControllerLWC {
    @AuraEnabled(cacheable=true)
    public static List<SObject> searchRecords(String objName,
                String fieldApiName, String searchVal){
        try {
            String key = '%' + searchVal + '%';
            String query = 'SELECT Id,'+ fieldApiName + ' FROM '+
                objName +' WHERE '+fieldApiName+' LIKE : key';
            List<SObject> lstObject = Database.query(query);
            return lstObject;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

2. Create recordList LWC component and copy paste below code into html file. 

<template>
    <div class="slds-grid slds-wrap slds-dropdown_length-with-icon-7
        slsd-dropdown_fluid slds-var-p-left_small">
        <div class="slds-col slds-size_4-of-4">
            <ul class="slds-listbox slds-listbox_vertical" role="presentation">
                <li class="slds-listbox__item">
                    <div class="slds-media slds-listbox__option
                        slds-listbox__option_entity slds-listbox__option_has-meta"
                        role="option" onclick={handleSelect}>
                        <span class="slds-media__figure slds-listbox__option-icon">
                            <lightning-icon
                              icon-name={iconname}
                              size="small"
                            ></lightning-icon>
                        </span>
                        <span class="slds-media__body"
                            style="padding-top: 9px;font-weight:600">
                            {record.Name}
                        </span>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</template>

Copy paste below code into recordList .js file

import { LightningElement, api } from 'lwc';

export default class RecordList extends LightningElement {
    @api record;
    @api iconname;

    handleSelect(){
        console.log('this.record.id '+this.record.Id);
        const selectedEvent = new CustomEvent(
            'select',
            {
                detail : this.record.Id
            }
        );
        this.dispatchEvent(selectedEvent);
    }
}

3. Create searchCmp LWC component and copy paste below code into html file

<template>
    <lightning-input
      type="text"
      variant="label-hidden"
      onchange={handleChange}
      value={searchValue}
    ></lightning-input>
</template>

Copy paste below code into searchCmp .js file

import { LightningElement, track } from 'lwc';

export default class SearchCmp extends LightningElement {
    @track searchValue;

    handleChange(event){
        const val = event.target.value;
        this.searchValue = val;

        const searchEvt = new CustomEvent(
            'searchevent',
            {
                detail : this.searchValue
            }
        );
        console.log('before dispatchEvent');
        this.dispatchEvent(searchEvt);
    }

}

4. Create customLookup LWC component and copy paste below code into html file

<template>
    <template if:false={selectedRec}>
        <c-search-cmp onsearchevent={handleSearchHandle}></c-search-cmp>
    </template>

    <template if:false={selectedRec}>
        <template if:true={records}>
            <template for:each={records} for:item="rec">            
                <c-record-list key={rec.Id} record={rec} iconname={iconname}
                onselect={handleSelect}></c-record-list>
            </template>
        </template>
    </template>

    <template if:true={selectedRec}>
        {selectedRec.Name}
    </template>

</template>

Copy paste below code into customLookup.js file

import { LightningElement, api, track } from 'lwc';
import searchRecords from '@salesforce/apex/CustomLookupControllerLWC.searchRecords'
export default class CustomLookup extends LightningElement {

    @api objectApiName ;
    @api fieldApiName;
    @api iconname;
    @track records;
    @track errors;
    @track selectedRec;

    handleSearchHandle(event){
        console.log('in handle event');
        const searchValue = event.detail;

        // Call apex method and create below Promise
        searchRecords({
            objName : this.objectApiName,
            fieldApiName : this.fieldApiName,
            searchVal : searchValue
        })
        .then(result => {
            console.log('Records are ', result);
            this.records = result;
            this.errors = undefined;
        })
        .catch(error =>{
            this.records = undefined;
            this.errors = error;
        })
    }

    handleSelect(event){
        console.log('in handleSelect ');
        const accId = event.detail;
        console.log('accId '+accId);
        const selectedRecord = this.records.find(
            rec => rec.Id === accId
        );
        /*
            above selectedRecord act like below
            this.records.find(account => account.Id === accountId);
            OR
            for(account acc : records){
                if(account.Id === accountId){
                    return acc;
                }
            }
        */
        console.log('Selected record ', selectedRecord);
        this.selectedRec = selectedRecord;
    }
}

Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers:


How to pass parameters in @wire method in LWC

 Syntax :

@wire(ApexMethodName, {key: value})

for example:

@wire(getAllCases, {strOrigin :'$sampleOrigin'})

here while assigning value to variable, in our example (sampleOrigin) we have to add '$' to bind value before sending to Apex.


Create Apex class : CaseController

public with sharing class CaseController {
    @AuraEnabled(cacheable= true)
    public static List<Case> getAllCases(String strOrigin){
        try {
             List<Case> lstCase = [SELECT Id, Subject, Origin
                                FROM Case WHERE Origin=: strOrigin];
             return lstCase;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

wireMethod.html

<template>
    <lightning-card title="All Cases" icon-name="standard:case" variant="base">
     <div>
        <lightning-input type="text" value ={sampleOrigin}
        label="Search" onchange={handleChange}></lightning-input>      
     </div>
      <div>
        <!-- Card Body  -->
        <template for:each={records} for:item="objItem">
            <p key={objItem.Id}>
                {objItem.Subject} <br/> {objItem.Origin}
            </p>
        </template>
        <template if:true={errors}>
            Something goes wrong.
        </template>
      </div>
    </lightning-card>
</template>

wireMethod.js

import { LightningElement, wire, api, track } from 'lwc';
import getAllCases from '@salesforce/apex/CaseController.getAllCases';
export default class WireMethod extends LightningElement {
    @api records;
    @api errors;
    @
track sampleOrigin;
    
    handleChange(event){
        const temp = event.target.value;
        this.sampleOrigin = temp;
    }

    /*
        @wire(ApexMethodName, {key: value})
            wiredCase ({ data, error }){
                - data => return list of case
                - error => error in for, of object
            }
    */
   @wire(getAllCases, {
        strOrigin :'$sampleOrigin'
    })
            wiredCase ({
                data, error
            }){
                if(data){
                    this.records = data;
                    this.errors = undefined;
                }
                if(error){
                    this.records = undefined;
                    this.errors = error;
                }
            }
}


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers:

2 ways to call Apex method using @wire in LWC

 In this blog, we are going to see 2 way to call apex class method using @wire in LWC.


Create Apex class : CaseController

public with sharing class CaseController {
    @AuraEnabled(cacheable= true)
    public static List<Case> getAllCases(){
        try {
            List<Case> lstCase = [SELECT Id, Subject, Origin FROM Case];
            return lstCase;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

1 : @wire(ApexMethodName) variableName;

Create Lightning web component : wireMethod.html

<template>
    <lightning-card title="All Cases" icon-name="standard:case" variant="base">
      <div>
        <!-- Card Body  -->
        <template for:each={caseList.data} for:item="objItem">
            <p key={objItem.Id}>
                {objItem.Subject} <br/> {objItem.Origin}
            </p>
        </template>
        <template if:true={caseList.error}>
            Something goes wrong.
        </template>
      </div>
    </lightning-card>
</template>

wireMethod.js

import { LightningElement, wire } from 'lwc';
import getAllCases from '@salesforce/apex/CaseController.getAllCases';
export default class WireMethod extends LightningElement {

    /*
        @wire(getAllCases) caseList;
        caseList have 2 parameters
        - data : returned data by apex
        - error : contains error if any
    */
   
    @wire(getAllCases) caseList;
}


2 : @wire(ApexMethodName) variableName;

wireMethod.html

<template>
    <lightning-card title="All Cases" icon-name="standard:case" variant="base">
      <div>
        <!-- Card Body  -->
        <template for:each={records} for:item="objItem">
            <p key={objItem.Id}>
                {objItem.Subject} <br/> {objItem.Origin}
            </p>
        </template>
        <template if:true={errors}>
            Something goes wrong.
        </template>
      </div>
    </lightning-card>
</template>

wireMethod.js

import { LightningElement, wire, api } from 'lwc';
import getAllCases from '@salesforce/apex/CaseController.getAllCases';
export default class WireMethod extends LightningElement {
    @api records;
    @api errors;
    /*
        @wire(getAllCases)
            wiredCase ({ data, error }){
                - data => return list of case
                - error => error in for, of object
            }
    */
   @wire(getAllCases)
            wiredCase ({
                data, error
            }){
                if(data){
                    this.records = data;
                    this.errors = undefined;
                }
                if(error){
                    this.records = undefined;
                    this.errors = error;
                }
            }
}


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers:

Easy Steps to Call Child Method with Parameter's from Parent in LWC

  In this blog, I am explaining how we can call Child method with multiple parameters' from Child component to Parent component in LWC.

parentCmp.html

<template>
    <div>
        <strong>I am from inside Parent</strong>
        <br/>
        <div>
            <lightning-button
                variant="brand"
                label="Change Date"
                title="Change Date"
                onclick={handleDateClick}>
            </lightning-button>
        </div>
    </div>
</template>

parentCmp.js

import { LightningElement } from 'lwc';

export default class ParentCmp extends LightningElement {
    handleDateClick(){
      this.template.querySelector('c-child-cmp').childMethod('From Parent', '42');
    }
}

childCmp.html

<template>
    <strong>I am from inside Child</strong>
    <p>  message - {message} </p>
    <p>  pageno - {pageno}   </p>
    <p>  Date is - {date}   </p>
</template>

childCmp.js

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

export default class ChildCmp extends LightningElement {
    @api message ;
    @api pageno;
    @track date = new Date();

    @api
    childMethod(msgFromParent, pageNumber){
        this.date = new Date();
        this.message = msgFromParent;
        this.pageno = pageNumber;
    }
}

Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers: