Chapter 32: Call Apex Method Imperatively in Lightning Web Component

 

Hello Friends, in this chapter we will learn how to call apex method imperatively. I hope you enjoy the article.

Are you ready ? Let’s Begin !!

 

 

Example 1

apexImperativeMethod.html

<template>
    <lightning-card title="ApexImperativeMethod" icon-name="custom:custom63">
        <div class="slds-var-m-around_medium">
            <p class="slds-var-m-bottom_small">
                <lightning-button
                    label="Load Contacts"
                    onclick={handleLoad}
                ></lightning-button>
            </p>
            <template if:true={contacts}>
                <template for:each={contacts} for:item="contact">
                    <div key={contact.Id}>
                    <p>{contact.Name}</p>
                    <p>{contact.Phone}</p>
                </div>
                </template>
            </template>
          
        </div>
    </lightning-card>
</template>

apexImperativeMethod.js

import { LightningElement } from 'lwc';
import getContactList from '@salesforce/apex/ContactMaster.getContactList';

export default class apexImperativeMethod extends LightningElement {
    contacts;
    error;

    handleLoad() {
        getContactList()
            .then((result) => {
                this.contacts = result;
                this.error = undefined;
            })
            .catch((error) => {
                this.error = error;
                this.contacts = undefined;
            });
    }
}

AccountManager.apxc

public class AccountManager {
      @AuraEnabled (cacheable=true)
      public static List <Account> getAccounts() {
        return [SELECT Id, name, industry, Type, NumberOfEmployees, TickerSymbol, Phone, Rating, Website, AnnualRevenue
                FROM Account ORDER BY createdDate ASC LIMIT 25];
      }
    
}

Example 2:

ApexImperativeMethodWithParams.html

<template>
    <lightning-card
        title="ApexImperativeMethodWithParams"
        icon-name="custom:custom63"
    >
        <div class="slds-var-m-around_medium">
            <lightning-layout
                vertical-align="end"
                class="slds-var-m-bottom_small"
            >
                <lightning-layout-item flexibility="grow">
                    <lightning-input
                        type="search"
                        onchange={handleKeyChange}
                        label="Search"
                        value={searchKey}
                    ></lightning-input>
                </lightning-layout-item>
                <lightning-layout-item class="slds-var-p-left_xx-small">
                    <lightning-button
                        label="Search"
                        onclick={handleSearch}
                    ></lightning-button>
                </lightning-layout-item>
            </lightning-layout>
            <template if:true={contacts}>
                <template for:each={contacts} for:item="contact">
                    <p key={contact.Id}>{contact.Name}</p>
                </template>
            </template>
        </div>

    </lightning-card>
</template>

ApexImperativeMethodWithParams.js

import { LightningElement } from 'lwc';
import findContacts from '@salesforce/apex/ContactMaster.findContacts';

export default class ApexImperativeMethodWithParams extends LightningElement {
    searchKey = '';
    contacts;
    error;

    handleKeyChange(event) {
        this.searchKey = event.target.value;
    }

    handleSearch() {
        findContacts({ searchKey: this.searchKey })
            .then((result) => {
                this.contacts = result;
                this.error = undefined;
            })
            .catch((error) => {
                this.error = error;
                this.contacts = undefined;
            });
    }
}

AccountManager.apxc

public class AccountManager {
      @AuraEnabled (cacheable=true)
      public static List <Account> getAccounts() {
        return [SELECT Id, name, industry, Type, NumberOfEmployees, TickerSymbol, Phone, Rating, Website, AnnualRevenue
                FROM Account ORDER BY createdDate ASC LIMIT 25];
      }
    
     @AuraEnabled
    public static List <Account> fetchAccountDetails(String accName){
        if(string.isNotBlank(accName)){
            string searchName ='%'+accName+'%';
            return [Select Id, name, industry, Type, NumberOfEmployees, TickerSymbol, Phone, Rating, Website, AnnualRevenue
                FROM Account where name like :searchName LIMIT 1];
        } 
        else{
            return NULL;
        }  
  }
}

 

Example3

opportunityManager.html

<template>
    <div class="slds-box slds-p-around_small" style="background-color: rgb(187, 255, 255);">
        <lightning-input label="Enter Opportunity Name"
                        placeholder="Opportunity Name"
                        value={searchOpportunityName}
                        onchange={opportunityNameChange}>
        </lightning-input>
        <template if:true={opportunities}>
            <div class="slds-grid slds-wrap sds-gutters">
                <template for:each={opportunities} for:item="opp">
                    <div class="slds-col slds-size_1-of-3 slds-p-around_small" key={opp.Id}>
                        <lightning-card title={opp.Name}>
                            <div slot="actions">
                                <template if:true={opp.IsClosed}>
                                    <span style="color: blue; font-weight: bold;">Already Closed</span>
                                </template>
                                <template if:false={opp.IsClosed}>
                                    <lightning-button   name={opp.Id}
                                                        value={opp.Id}
                                                        label="Close Opportunity"
                                                        onclick={passOpportunityToClose}
                                    ></lightning-button>
 
                                </template>
                            </div>
                        
                            <p class="slds-p-horizontal_small">
                                <span style="color: blue;">Stage:</span>{opp.StageName}  
                              </p>
                              <p class="slds-p-horizontal_small">
                                <span style="color: blue;">Close Date:</span>{opp.CloseDate}  
                              </p>
                        
                        </lightning-card>
                    </div>
                </template>
            </div>
        </template>
    </div>    
</template>

opportunityManager.js

import { LightningElement } from 'lwc';
import fetchOpportunityDetails from '@salesforce/apex/OpportunityManager.fetchOpportunityDetails';
import closeOpportunity from '@salesforce/apex/OpportunityManager.closeOpportunity';
export default class CaseManager extends LightningElement {
    searchOpportunityName;
    opportunities;
    errorDetails;
    opportunityCloseMessage;

    opportunityNameChange(event){
        this.searchOpportunityName = event.target.value;
        fetchOpportunityDetails({oppName:this.searchOpportunityName
        })
        .then(result=>{
            this.opportunities = result;
        })
        .catch(error=>{
            this.errorDetails = error;
        });
    }
    passOpportunityToClose(event){
        this.opportunityId = event.target.name;
        closeOpportunity({opportunityId:this.opportunityId})
        .then(result=>{
            this.opportunityCloseMessage = result;
        })
        .catch(error=>{
           this.errorDetails = error; 
        });
    }
}

OpportunityManager.apxc

public class OpportunityManager {
     @AuraEnabled
    public static list<Opportunity> fetchOpportunityDetails(string oppName){
        if(string.isNotBlank(oppName)){
            string searchOpp ='%'+oppName+'%';
            return [SELECT Id,Account.Name,Name,StageName, CloseDate
                    FROM Opportunity
                    where Name like :searchOpp];
        } 
        else{
            return NULL;
        }   
    }
    @AuraEnabled
    public static string closeOpportunity(string opportunityId){
        string message;
        try{
            opportunity opp = new opportunity(Id=opportunityId);
            opp.StageName='Closed Won';
            update opp;
            message = 'Success';
        }   
        catch(Exception ex){
            message = ex.getMessage();
        } 
        return message;
    }

}

 

 

 

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes