Introduction:
In Salesforce Aura components, we often need to retrieve data from the server-side by invoking Apex methods. This allows us to fetch or manipulate data stored in Salesforce and use it within our component’s JavaScript controller. In this blog post, we will discuss how to call an Apex method in a JS controller to fetch a list of holidays using a practical example.
Code Example:
Step 1: Create the Apex Method First, let’s create an Apex method named get holidays
to fetch the holiday records from the “Leave_calendar__c” object.
@AuraEnabled
public static List<Leave_calender__c> getholidays(){
List<Leave_calender__c> holilist = new List<Leave_calender__c>();
holilist = [SELECT Id, Name, Date__c, Day__c, Holidays_type__c FROM Leave_calender__c];
return holilist;
}
Step 2: Call the Apex Method in the JS Controller Next, we’ll call the getholidays
Apex method from our JavaScript controller to retrieve the holiday data and store it in a component attribute.
doInit : function(component, event, helper) {
var employeid = component.get("v.EmpId");
var action = component.get("c.getholidays");
action.setCallback(this, function(response) {
var holilist = response.getReturnValue();
console.log('holilist@@@', holilist);
component.set("v.holidaylist", holilist);
});
$A.enqueueAction(action);
}
Explanation:
- In the
doInit
function, we start by retrieving theEmpId
value from the component usingcomponent.get("v.EmpId")
. - We then create an action variable by referencing the
getholidays
Apex method usingcomponent.get("c.getholidays")
. - Next, we set up a callback function using
setCallback(this, function(response) {...})
to handle the response returned from the server-side action. - Inside the callback function, we retrieve the holiday data using
response.getReturnValue()
, which contains the list of holidays returned by the Apex method. - Finally, we log the retrieved holiday data to the console using
console.log()
and set it to the component’sholidaylist
attribute usingcomponent.set("v.holidaylist", holilist)
.
Conclusion:
In this blog post, we learned how to call an Apex method from a JavaScript controller in a Salesforce Aura component. By following the steps outlined above, we successfully fetched a list of holidays from a custom object and stored it in a component attribute. Leveraging Apex methods in JS controllers allows us to bring server-side functionality into our Aura components, enabling powerful interactions with Salesforce data.
Summary:
In this blog post, we will demonstrate how to call an Apex method from a JavaScript controller in a Salesforce Aura component. We’ll create an Apex method that retrieves a list of holidays from a custom object called “Leave_calendar__c.” Then, we’ll invoke this method in the JavaScript controller’s doInit
function to retrieve the holiday data and store it in a component attribute. Let’s dive into the code and explore the implementation steps.
Hits: 0