~ read.

Replacing OnClick Javascript button with Lightning Component

Lightning seems to be all the rage these days! How could it not be? It is the present day reality and changes the way Salesforce developers need to think when coming up with their solutions on the platform. One of the most common challenge you will come across is to replicate the functionality of an OnClick Javascript button.

In Salesforce Aloha, these buttons provided us a nifty way to call our Apex controllers and even pass parameters such as Account Id, etc. You can still achieve the same result in Lightning, however you have to take a different path. Enough talk, let's start!

Old Solution

{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")} 
{!REQUIRESCRIPT("/soap/ajax/10.0/apex.js")} 
var result = sforce.apex.execute("genericOutput","generate", {genericId:"{!Account.Id}"});  
window.alert(result );  
window.location.reload(true);  

Let's assume you have a genericOutput class that has generate method that accepts Id genericId which is an Account Id.

Create a Lightning Solution

Component:

You should use force:hasRecordId to pass AccountId to your Apex controller. Others are optional but are recommended for their specific use cases which you can read here.

<aura:component controller="YourApexController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >  
    <!-- Define Attribute For Current recordId -->
    <aura:attribute name="recordId" type="Id" />
    <!-- Define Attribute To Open Pop-up --> 
    <aura:attribute name="yesNoOptions" type="boolean" default="false"/>

    <!--- Display Pop-Up For Yes/No Option To Perform Your Action. --> 
    <aura:if isTrue="{!v.yesNoOptions}">
      <div role="alertdialog" tabindex="-1" aria-labelledby="prompt-heading-id" aria-describedby="prompt-message-wrapper" class="slds-modal slds-fade-in-open slds-modal--prompt">
         <div class="slds-modal__container">
            <div class="slds-modal__header slds-theme--success slds-theme--alert-texture">
               <h2 class="slds-text-heading--medium" id="prompt-heading-id">Heading As per Your Choice</h2>
            </div>
            <div class="slds-modal__content slds-p-around--medium">
               <div>
                  <p>Header For Your Model Pop-up Box</p>
               </div>
            </div>
            <div class="slds-modal__footer slds-theme--default">
               <!-- If User Clicks Yes Then Call Controller Action.-->
               <button class="slds-button slds-button--brand" onclick="{!c. functionaName}">Yes</button>
                <!-- If User Clicks No Then Close Pop-up.-->
               <button class="slds-button slds-button--brand" onclick="{!c.closeMessage}">No</button>
            </div>
         </div>
      </div>
      <div class="slds-backdrop slds-backdrop--open"></div>
    </aura:if>
    <!-- Add Component Description -->
        <div class="slds-m-around--medium" >
           <div class="slds-container--medium">
            <div class="slds-form--stacked">
              <div class="slds-form-element">                
                Add Description here which will explain What this component is About <br/>
              </div>
              <div class="slds-form-element">                
                  <!---Button Which Will Open Pop-up--> 
                  <button class="slds-button slds-button--brand" style="margin-
                          left: 39%;" onclick="{!c.openDialog}">Your Button Name</button>

              </div>
              <br/>              
            </div>
        </div>
    </div>   
</aura:component>

Controller:

Use the following component controller to get the AccountId.

//This is method of your Component controller
    functionName : function(component, event, helper) {
         //get AccountId
         var getAccountId = component.get("v.recordId");

         helper.myHelperFunction(component,getAccountId );

     },

     //When a User Clicks on Your Button inside the Component, this will open 
      //Dailog with Yes/No Option, you can configure buttons and name of buttons as per your choice.
     openDialog: function(component, event, helper) {
         component.set("v.yesNoOptions", true);        
     },

     //Hide Dailog Box by setting attribute to false 
     closeMessage: function(component, event, helper) {       
        component.set("v.yesNoOptions", false);        
     },

Javascript:

Now, send parameter to your Apex Controller. For the sake of this example I am passing 1 parameter. You can pass several as per you requirement.

myHelperFunction: function(component,getAccountId ) {  
        //Call Your Apex Controller Method.
        var action = component.get("c.yourApexControllermethod");
        // set Account RecordId to yourApexController method, parameter name should be exact match as that of apex method parameter name.   
        action.setParams({
            'genericId': getAccountId 
        });

        action.setCallback(this, function(response) {
            var state = response.getState();
                if (state === "SUCCESS") {
                    //Do Something
                } else {
                    //Do Something
                }
            }            
        });
        $A.enqueueAction(action);
    },

Add the @AuraEnabled annotation to your Apex method.

public class YourApexClass {  
     @AuraEnabled
    public static String yourApexControllermethod (Id genericId) {
         //Do Something , you have your AccountId here
           //As parameter list goes up, you need to add parameters here "," seperated
    }
}

Now, add the newly created Lightning Component to Account Record Page using Lightning App builder or create a New Action and attach it to the Component.

Let me know your thoughts in comments.

comments powered by Disqus