Call Apex Method With Parameters in Lightning Web Component

In Salesforce Apex classes, we can define class methods in two ways: one without parameters, where we simply want to fetch static data in the LWC component by calling the Apex method. The other method is with parameters, which are mapped with input fields in the Lightning web component and used in scenarios such as creating or searching for records.

In this Salesforce tutorial, we will learn how to call the Apex method with parameters in Lightning Web Component.

What is an Apex Call With Parameters?

An Apex call with parameters refers to the method of invoking or triggering an Apex method from a Lightning Web Component (LWC) or another Salesforce component by passing input values (parameters) to the method.

These parameters are used within the Apex method to perform operations such as querying, creating, updating, or deleting Salesforce records based on user input.

Call Apex Method With Parameters in Lightning Web Component

In the example below, we create an Apex controller class with defined parameters, and we will call that Apex class in the Lightning web component to create opportunity records.

We will fetch the Apex method from the controller class with parameters using the @wire decorator.

  1. Create an apex controller class that will take the parameters to create the opportunity records.
public class OpportunityController {
    @AuraEnabled
    public static Id createOpportunity(String oppName, Decimal oppAmount, Date closeDate) {
        try {
            Opportunity opp = new Opportunity();
            opp.Name = oppName;
            opp.Amount = oppAmount;
            opp.CloseDate = closeDate;
            opp.StageName = 'Prospecting';
            
            insert opp;
            return opp.Id;
        } catch(Exception ex) {
            System.debug('An Exception error occurred: ' + ex);
            return null;
        }
    }
}

In this controller class, we have included the parameters to take the input for the fields opportunity name, amount, close date, and prospecting.

  1. After this, create a Lightning web component and enter the code below in the JS file to define the logic for creating an opportunity record.

In the JS file, we have imported the createOpportunity method from the Apex controller class.

import { LightningElement, track, wire } from 'lwc';
import createOpportunity from '@salesforce/apex/OpportunityController.createOpportunity';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class OpportunityCreator extends LightningElement {
    @track oppName = '';
    @track oppAmount = null;
    @track oppCloseDate = null;
    @track oppId;
    @track error;

    handleNameChange(event) {
        this.oppName = event.detail.value;
    }

    handleAmountChange(event) {
        this.oppAmount = event.detail.value;
    }

    handleCloseDateChange(event) {
        this.oppCloseDate = event.detail.value;
    }

    @wire(createOpportunity, { oppName: '$oppName', oppAmount: '$oppAmount', closeDate: '$oppCloseDate' })
    wiredOpportunity({ error, data }) {
        if (data) {
            this.oppId = data;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Opportunity created successfully with ID: ' + this.oppId,
                    variant: 'success'
                })
            );
        } else if (error) {
            this.error = error;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error',
                    message: 'Error creating opportunity: ' + error.body.message,
                    variant: 'error'
                })
            );
        }
    }
}

In the above code, we have used the @wire decorator to track the changes in the input fields.

We have created events handleNameChange(), handleAmountChange(), and handleCloseDateChange() to update the parameters from the controller class, opp.Name, opp.Amount and opp.Stage.

At last, Submit action will call the createOpportunity apex method with the component’s property values.

  1. After this, enter the code below in the HTML file to define the UI of the Lightning web component.

In this, we have defined the input fields: opportunity name, amount, and close date. At last, there is a Submit button that will call the handleSubmit method and create the opportunity record.

<template>
    <div class="slds-box slds-theme_default">
        &