In below example I’m creating Lead records from a Lightning Component. On Save button I’ve implemented the logic to hide the button after click.
Apex Controller:
public class SampleAuraController { @AuraEnabled Public static void createLead(Lead objLead){ try{ //Insert Lead Record insert objLead; }catch(Exception e){ //get exception message throw new AuraHandledException(e.getMessage()); } finally { } } }
Lightning Component:
<!--Sample.cmp--> <aura:component controller="SampleAuraController" implements="flexipage:availableForAllPageTypes,force:appHostable"> <!--Declare Attributes--> <aura:attribute name="isSpinner" type="boolean" default="false"/> <aura:attribute name="objLead" type="Lead" default="{'sobjectType':'Lead', 'FirstName': '', 'LastName': '', 'Email': '', 'Company': ''}"/> <!--Declare Handlers--> <aura:handler event="aura:waiting" action="{!c.handleShowSpinner}"/> <aura:handler event="aura:doneWaiting" action="{!c.handleHideSpinner}"/> <!--Component Start--> <div class="slds-m-around--xx-large"> <div class="container-fluid"> <div class="form-group"> <lightning:input name="fname" type="text" maxlength="50" required="true" label="First Name" value="{!v.objLead.FirstName}" /> </div> <div class="form-group"> <lightning:input name="lname" type="text" maxlength="50" required="true" label="Last Name" value="{!v.objLead.LastName}" /> </div> <div class="form-group"> <lightning:input name="emailId" type="email" maxlength="100" required="true" label="Email" value="{!v.objLead.Email}" /> </div> <div class="form-group"> <lightning:input name="company" type="text" maxlength="50" required="true" label="Company" value="{!v.objLead.Company}" /> </div> </div> <br/> <lightning:button variant="brand" disabled="{!v.isSpinner}" label="{!v.isSpinner == true ? 'Saving...' : 'Save'}" onclick="{!c.handleLeadSave}" /> </div> <!--Component End--> </aura:component>
Lightning JS Controller:
({ //Handle Lead Save handleLeadSave : function(component, event, helper) { var objLead = component.get("v.objLead"); var action = component.get("c.createLead"); action.setParams({ objLead : objLead }); action.setCallback(this,function(a){ var state = a.getState(); if(state === "SUCCESS"){ alert('Record is Created Successfully'); } else if(state === "ERROR"){ var errors = action.getError(); if (errors) { if (errors[0] && errors[0].message) { alert(errors[0].message); } } }else if (status === "INCOMPLETE") { alert('No response from server or client is offline.'); } }); $A.enqueueAction(action); }, //Call by aura:waiting event handleShowSpinner: function(component, event, helper) { component.set("v.isSpinner", true); }, //Call by aura:doneWaiting event handleHideSpinner : function(component,event,helper){ component.set("v.isSpinner", false); } })