Back to Top

Add LWC Quick Action to Salesforce Field Service Mobile App

Updated 9 January 2025

Are you looking to enhance your Salesforce Field Service Mobile App with custom functionality?

In this guide, we’ll walk you through the steps to add a Lightning Web Component (LWC) Quick Action to the Field Service Mobile App.

By using Lightning Web Component Quick Actions, you can introduce custom features that go beyond the standard capabilities of the Field Service Mobile App, enabling a more tailored user experience.

Explore more solutions offered by Webkul.

Prerequisite: Enable Lightning SDK in the Field Service Mobile App

Before proceeding, ensure that you’ve completed the following:

Searching for an experienced
Salesforce Company ?
Find out More
  1. Navigate to the System Permissions of the permission set assigned to your Service Resource.
  2. Enable the checkbox for “Enable the Lightning SDK for online and offline use in the Field Service mobile app.”
    • Note: If the Lightning SDK for Field Service Mobile org setting is enabled, it will override this permission.

Without this crucial setting, the Lightning Web Component Quick Action will not appear in the Field Service Mobile App.

Why Use Salesforce Field Service Mobile App?

The Field Service mobile app for Android and iOS offers a comprehensive tool for today’s mobile workforce.

Built with an offline-first approach, it allows you to work and save changes even without internet access. You can also customize the app to meet your specific business requirements.

What is a Lightning Web Component Quick Action?

Lightning Web Component (LWC) quick actions empower users to perform tasks in Salesforce with ease by directly invoking custom Lightning Web Components on record pages.

With custom quick actions, you streamline navigation and workflows, giving users quick access to the most important information.

These intuitive UI buttons enhance productivity by delivering the tools and data they need at their fingertips.

How to Set Up a Lightning Web Component as a Quick Action on a Record Page?

Set up a Lightning Web Component (LWC) as a quick action on a record page by defining the metadata in the <component>.js-meta.xml file.

Specify a lightning__RecordAction target and set isExposed to true to make the component accessible as a quick action.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>62.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordAction</target>
    </targets>
</LightningComponentBundle>

Follow these simple steps to create a Lightning Web Component (LWC) Quick Action in Salesforce and add it to the page layout:

  1. Navigate to Setup.
  2. Go to Object Manager and select the object where you want to create the Quick Action.
  3. Click on Buttons, Links, and Actions and then select New Action.
  4. Choose Action Type as Lightning Web Component.
  5. Select the desired component, specify the name and label, and click Save.
  6. Add the newly created Quick Action to the Page Layout of the object.

Use Case: Enhancing Work Order Management with LWC Quick Action

Imagine using an LWC Quick Action that allows Service Resources to effortlessly upload and view images related to a Work Order.

This feature streamlines work order management, enabling field technicians to document and access visual information directly within the Salesforce Field Service Mobile App.

Work Order Quick Action

The Following Apex class will work as the controller for the Lightning Web Component Quick Action

public with sharing class FileClass {
    /**
    * @description Method to retrieve the related images
    * @param linkedEntityId the Salesforce recordId
    * @return  `List<ContentVersion>` List of related images
    */
    @AuraEnabled
    public static List<ContentVersion> wkGetFiles(String linkedEntityId){
        List<String> fileTypes=new List<String>{'JPEG','JPG','PNG'};
        Set<Id> contentDocumentIds = new Set<Id>();
        for (ContentDocumentLink link : [
            SELECT ContentDocumentId
            FROM ContentDocumentLink
            WHERE LinkedEntityId =:linkedEntityId
        ]) {
            contentDocumentIds.add(link.ContentDocumentId);
        }
        return [
            SELECT Id, Title, ContentDocumentId, FileType, VersionData
            FROM ContentVersion
            WHERE ContentDocumentId IN :contentDocumentIds
            AND IsLatest = true AND FileType IN:fileTypes ORDER BY CreatedDate Asc
        ];
    }
    /**
     * @description Method to create ContentVersion records
     * @param fileName Name of the file
     * @param base64Data the image converted to base64 
     * @param parentId RecordId of the related record
     * @return  `String` record Id of the inserted
     * @exception 
     */
    @AuraEnabled
    public static String createContentVersion(String fileName, String base64Data, String parentId) {
        try {
            // Decode the base64 string
            Blob fileBody = EncodingUtil.base64Decode(base64Data);
            // Create the ContentVersion record
            ContentVersion contentVersion = new ContentVersion();
            contentVersion.Title = fileName;
            contentVersion.PathOnClient = fileName;
            contentVersion.VersionData = fileBody;
            if (String.isNotBlank(parentId)) {
                contentVersion.FirstPublishLocationId = parentId; // Link to a record (optional)
            }
            insert contentVersion;
            // Return the Id of the created ContentDocument
            return contentVersion.Id;
        } catch (Exception e) {
            throw new AuraHandledException('Error uploading file: ' + e.getMessage());
        }
    }
}

The Lightning Web Component will be implemented like this

HTML File

<template>
    <template if:true={showSpinner}>
        <lightning-spinner alternative-text="Uploading..." size="small"></lightning-spinner>
    </template>
    <div class="container">
        <template lwc:if={showFile}>
            <div class="slds-text-heading_medium">
                Attachments
            </div>
            <div class="slds-grid slds-wrap">
                <template for:each={files} for:item="file">
                    <div class="slds-col slds-m-around_small slds-align_absolute-center" key={file.Id}>
                        <img src={file.source} alt="" style="max-width: 140px;">
                    </div>
                </template>
            </div>
        </template>
        <template lwc:else>
            <h1>No Attachments</h1>
        </template>      
        <div class="slds-grid slds-grid_vertical">
            <div class="slds-col slds-m-around_small slds-align_absolute-center">
                <strong>{fileName}</strong>
                <lightning-input type="file" accept=".png, .jpg, .jpeg," onchange={handleFileChange}></lightning-input>
            </div>
            <div class="slds-col slds-m-around_small slds-align_absolute-center">
                <lightning-button label="Upload" onclick={uploadFile} variant="brand" class="s-margin-top" disabled={isUploadDisabled}></lightning-button>
                <lightning-button label="Refresh View" onclick={refreshView} class="slds-m-left_small"></lightning-button>
            </div>
        </div>
    </div>
</template>

Javascript File

import { LightningElement,api,track } from 'lwc';
import wkGetFiles from "@salesforce/apex/FileClass.wkGetFiles";
import createContentVersion from "@salesforce/apex/FileClass.createContentVersion"

export default class wkWorkOrderAttachments extends LightningElement {
    @api recordId;
    @track files=[];
    imgList=[];
    showFile=false;
    showSpinner=false;
    fileName;
    fileContent;
    isUploadDisabled=true;
    connectedCallback(){
        this.getRelatedImages();
    }
    getRelatedImages(){
        this.showSpinner=true;
        wkGetFiles({linkedEntityId:this.recordId}).then(response=>{
            if(response!=null){
                this.imgList=response;
                for(let i=0;i<this.imgList.length;i++){
                    let image = {
                        Id: this.imgList[i].Id,
                        Title: this.imgList[i].Title,
                        source:window.location.origin + "/sfc/servlet.shepherd/version/renditionDownload?rendition=THUMB720BY480&versionId=" +this.imgList[i].Id +"&operationContext=CHATTER&contentId=" +this.imgList[i].ContentDocumentId
                      };
                      this.files.push(image);
                }
            }
            this.showFile=true;
            this.showSpinner=false;
        })
    }
    handleFileChange(event){
        const file = event.target.files[0];
        if (file) {
            this.fileName = file.name;
            const reader = new FileReader();
            reader.onload = () => {
                const base64 = reader.result.split(',')[1];
                this.fileContent = base64;
                this.isUploadDisabled = false;
            };
            reader.readAsDataURL(file);
        }
    }
    async uploadFile() {
        if (this.fileContent && this.fileName) {
            this.showSpinner = true;
            try {
                const result = await createContentVersion({
                    fileName: this.fileName,
                    base64Data: this.fileContent,
                    parentId: this.recordId,
                });
                this.uploadedFileId = result;
                this.showSpinner = false;
                this.isUploadDisabled = true;
                this.files=new Array();
                this.fileContent=null;
                this.fileName=null;
                this.connectedCallback();
            } catch (error) {
                this.showSpinner = false;
            }
        }
    }
    refreshView(){
        this.isUploadDisabled = true;
        this.files=new Array();
        this.fileContent=null;
        this.fileName=null;
        this.connectedCallback();
    }
}

Example

Conclusion

The Field Service Mobile App is a powerful tool designed for field technicians to efficiently manage tasks on the go.

It offers customizable features that integrate seamlessly with Salesforce Field Service, enabling businesses to streamline operations and enhance customer satisfaction.

Additionally, Lightning Web Component Quick Actions enable users to add custom features that extends capabilities of the Field Service Mobile App.

For any queries regarding Field Service Lightning or personalized solutions, contact our expert Salesforce Consultants at [email protected] or via Live Chat.

Our team is available year-round to provide customized solutions tailored to your business needs.

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home