Lightning Component Quick Actions

Introductions

In this blog, I am going to explain how to custom actions to customize lightning and  Salesforce1 experiences with both global actions and quick actions. Global actions are not associated with any object means you can insert data that is not going to establish any relations other record and Object-specific actions are associated with the object so it allows creating records that have automatic relationships to other records, make updates to specific records. To available Lightning component as actions, you need to implement either the force: LightningQuickAction or force: LightningQuickActionWithoutHeader interfaces.Add the force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the current record. When we implement the force:lightningQuickAction interface display in a panel with standard action controls, such as a Cancel button. If instead, you want complete control over the user interface, use the force: lightningQuickActionWithoutHeader interface. Components that implement the force:lightningQuickActionWithoutHeader display in a panel without additional controls and are expected to provide a complete user interface for the action.

Object-Specific Actions
What we are going to do it here, we will create a quick action that is going to create a quote from the opportunity. Create an apex class as shown below and the apex class is used to communicate to server-side actions to save the Quote.

public class QuickQuote {
    @AuraEnabled
    public static boolean saveQuote(Quote newQuote, Id oppId) {
        system.debug('newQuote'+newQuote);
        newQuote.OpportunityId = oppId;
        try{
            insert newQuote ; 
            return true ;
        }catch(Exception e){
            throw new AuraHandledException(e.getMessage());
            return false ;
        }
        
    }
    
}

Go to developer console and create a new lightning component name ” Quick Quote” with below code

<aura:component controller="QuickQuote"
                implements="force:lightningQuickActionWithoutHeader">
    <aura:attribute name="recordId" type="String" />
    <aura:attribute name="newQuote" type="Quote"
                    default="{ 'sobjectType': 'Quote','Name':'Default Quote' , 
                             'ExpirationDate':'2017-10-30','Email':'test@email.com' ,'Phone':'' ,'Discount':'19' , 'BillingName':'Teest' }" /> 
    <div class="slds-page-header" role="banner">
        <h1 class="slds-page-header__title slds-m-right--small
                   slds-truncate slds-align-left">Create New Quote</h1>
    </div>
    <lightning:input aura:id="quoteName" 
                     name="Quote Name" 
                     label="Quote Name" 
                     value="{!v.newQuote.QuoteToName}"
                     required="true"/>
    <ui:inputDate aura:id="quoteDate" displayDatePicker="true"
                  label="Expiration Date" 
                  value="{!v.newQuote.ExpirationDate}"
                  />
    <lightning:input aura:id="quoteEmail"
                     name="Email Date" 
                     label="Email"
                     value="{!v.newQuote.Email}" 
                     Type="email"/>
    <lightning:input aura:id="quotePhone" 
                     name="Phone Date" 
                     label="Phone"
                     value="{!v.newQuote.Phone}"
                     Type="tel"/>
    
    <lightning:input aura:id="quoteDiscount" 
                     name="Discount" 
                     label="Discount"
                     value="{!v.newQuote.Discount}"
                     Type="number"/>
    
    <lightning:button label="Create Quote" onclick="{!c.createQuote}"
                      class="slds-m-top--medium"/>
    
    <lightning:button label="Cancel" onclick="{!c.handleCancel}" class="slds-m-top--medium" />
    
    
</aura:component>

Here is Lightning component controller code.

({
    createQuote: function(component, event, helper) {
        var saveAction = component.get("c.saveQuote");
        console.log('saveAction');
        saveAction.setParams({
            newQuote: component.get("v.newQuote"),
            oppId: component.get("v.recordId")  
             
        });
        saveAction.setCallback(this, function(response) {
            var state = response.getState();
            console.log('state'+state);
            if(state === "SUCCESS") {
                var resultsToast = $A.get("e.force:showToast");
                resultsToast.setParams({
                    "title": "Quote",
                    "message": "Quote Creation is Success."
                });
                $A.get("e.force:closeQuickAction").fire();
                resultsToast.fire();
                $A.get("e.force:refreshView").fire();
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                    errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            } 
        });
        console.log('En Quier action ');
        $A.enqueueAction(saveAction);
        
        
    },
    
    handleCancel: function(component, event, helper) {
        $A.get("e.force:closeQuickAction").fire();
    }
})

The createQuote action handler method will do the following action

  • Invoke server action to save the quote by calling component.get(“c.saveQuote”) from the apex class .
  • Defines a callback function to handle the server response.
  • Enqueues the server action by calling” $A.enqueueAction(saveAction)
  • handleCancel Closes the action panel by firing the force:closeQuickAction event.
  • Displays a “toast” message that the Quote was created by firing the force:showToast event.

Go to Opportunity and create an action as shown below.

Add it to the opportunity  Salesforce1 and Lightning Experience Actions section on the page layouts to create quote by using actions.

 

Global Actions

Now we are going to create global actions that allow users to create the new user from the global action.
create a new apex class “CreateNewUser” with the below code.

public class CreateNewUser {
    @AuraEnabled
    public static void insertNewUser(User userInsert ){
        try{
            
            User temp = userInsert ; 
            Database.DMLOptions dmo = new Database.DMLOptions();
            dmo.EmailHeader.triggerUserEmail = false;
            String profileId =[Select id from Profile where name = 'Chatter Free User' Limit 1] .Id;
            temp.ProfileId = ProfileId;
            temp.TimeZoneSidKey = 'America/Los_Angeles';
            temp.LanguageLocaleKey = 'en_US';
            temp.EmailEncodingKey ='UTF-8';
            temp.LocaleSidKey = 'en_US';
            temp.setOptions(dmo);
        
            insert temp ;  
        }catch(Exception e){
            throw new AuraHandledException(e.getMessage());
          }
        
    }
    
}

Go to developer console and create a new lightning component “CreateNewUser” with below code.

<aura:component controller="CreateNewUser" implements="force:lightningQuickActionWithoutHeader">
    
    
    <aura:attribute name="newUser" type="User"  default="{ 'sobjectType': 'User',
                                                         'FirstName':'' , 
                                                         'LastName':'',
                                                         'Email':'' ,
                                                         'Username':'' ,
                                                         'Alias':''
                                                         }" />
    
    
    <ui:inputtext label="First Name" value="{!v.newUser.FirstName}"/>
    <ui:inputtext label="Last Name" value="{!v.newUser.LastName}"/>
    <ui:inputemail label="Email" value="{!v.newUser.Email}"/>
    <ui:inputemail label="User Name" value="{!v.newUser.Username}"/>
    <ui:inputemail label="Alias" value="{!v.newUser.Alias}"/>
    
    <lightning:button label="Save " onclick="{!c.handleSave}"
                      variant="brand" class="slds-button slds-button_brand slds-col_bump-left"/>
    
    
       
</aura:component>

Here is the component controller.

({
    handleSave: function(component, event, helper) {
        
        var newUserInsert = component.get("c.insertNewUser");
        //console.log(newUserInsert)
        console.log(component.get("v.newUser"));
        newUserInsert.setParams({
            "userInsert": component.get("v.newUser")
        });
        
        console.log(newUserInsert);
        newUserInsert.setCallback(this, function(response) {
            console.log(response);
            var state = response.getState();
            if(state === "SUCCESS") {
                // Prepare a toast UI message
                var resultsToast = $A.get("e.force:showToast");
                resultsToast.setParams({
                    "title": "Record is  Created  !",
                    "message": response
                });
                // Update the UI: close panel, show toast, refresh account page
                $A.get("e.force:closeQuickAction").fire();
                resultsToast.fire();
                $A.get("e.force:refreshView").fire();
            }
            else if (state === "ERROR") {
                var errors = response.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        console.log("Error message: " + 
                                    errors[0].message);
                    }
                } else {
                    console.log("Unknown error");
                }
            } 
                else {
                    console.log('Unknown problem, response state: ' + state);
                }
        });
        
        // Send the request to create the new contact
        $A.enqueueAction(newUserInsert);
    }
    
    
},
 
 })

Go to Global action from the setup menu and create a new global action as shown below.

Go to publisher layout from the setup menu and add the lightning component create to the layout as shown below.

You can access global action from salesforce global header.