Overriding Salesforce File Fields When Files Uploaded Using Lightning File Upload LWC

Telegram logo Join our Telegram Channel
Overriding Salesforce File Fields When Files Uploaded Using Lightning File Upload LWC

Hello There, the Lightning File Upload component is the easiest way to upload files to Salesforce Files using the Lightning web component. But there is a limitation to it, we can't override the file name when the file is uploaded using Lightning File Upload. It retains the file name provided by the end-user while uploading and developers have no control over it.

But there is a workaround for this.

We can use the file-field-name and file-field-value attributes of the lightning-file-upload component to overwrite the file name, i.e. Title, or execute other business logic.

Let us understand this with an example.


Example Scenario - Set custom prefix to file Title when uploaded from Lightning File Upload

In this example, I explain how to add a prefix to a file title when it is uploaded from my custom LWC component named MyDocsUploader

Follow the steps below carefully.

  1. First, you have to create a custom field on the Content Version object, make sure that the custom field API name ends with fileupload__c.

    I have created the field with the API name Prefix_fileupload__c, to demonstrate with an example.

    This is what my field looks like,
    create a custom field on the Content Version ending with fileupload__c

    The custom field must end with fileupload__c otherwise the lightning-file-upload component can't set the value to the custom field.

  2. Create a Lightning web component to upload the file. Use the following code snippets in your LWC component.

    Set recordId, fileFieldName and fileNamePrefix from your component.

    JS

    import { LightningElement, wire } from "lwc";
    import { ShowToastEvent } from "lightning/platformShowToastEvent";
    
    // ...
    
    // !IMP - notice that field api name ends with "fileupload__c"
    import FILE_PREFIX from "@salesforce/schema/ContentVersion.Prefix_fileupload__c";
    
    export default class MyDocsUploader extends LightningElement {
    
        // set record ID to link file with record.
        recordId;
    
        // API name of the field used by file uploader component
        fileFieldName = FILE_PREFIX.fieldApiName;
    
        // set your prefix here/you can also set this dynamically.
        fileNamePrefix = "Uploaded-from-MyDocsUploader";
    
        // add supported file formats
        get acceptedFormats() {
            return [".pdf"];
        }
    
        // show toast once upload is finished
        handleUploadFinished(event) {
            // Get the list of uploaded files
            const uploadedFiles = event.detail.files;
    
            this.dispatchEvent(
                new ShowToastEvent({
                    title: "Upload Successful!",
                    message:
                        "Uploaded files: " +
                        uploadedFiles.map((file) => file.name).join(", "),
                    variant: "success"
                })
            );
        }
    
    }
    

    HTML

    Set the file-field-name and file-field-value from your LWC component.

    <lightning-file-upload
        label="Attach Your File"
        name="YourFileExample"
        accept={acceptedFormats}
        record-id={recordId}
        onuploadfinished={handleUploadFinished}
        file-field-name={fileFieldName}
        file-field-value={fileNamePrefix}
    >
    </lightning-file-upload>
    

  3. In the next step, we will use the Prefix_fileupload__c field value to overwrite the file Title. To achieve this, we need to write a simple trigger on the ContentVersion object.

    Let us write the trigger handler first.

    TriggerHandler

    public with sharing class ContentVersionTriggerHandler {
        public static void setFilePrefix(List<ContentVersion> newList) {
            for (ContentVersion cv : newList) {
                if (String.isNotBlank(cv.Prefix_fileupload__c)) {
                    cv.Title = (cv.Prefix_fileupload__c + ' - ' + cv.Title).left(255);
                }
            }
        }
    }
    

    Trigger

    trigger ContentVersionTrigger on ContentVersion(before insert) {
        if (Trigger.isBefore && Trigger.isInsert) {
            ContentVersionTriggerHandler.setFilePrefix(Trigger.new);
        }
    }
    

  4. And there you go! Now, when you upload the file from the MyDocsUploader component, it will prefix the original file name with Uploaded-from-MyDocsUploader.


Further customizations

  1. This workaround isn't just limited to changing the file title; you can also perform actions like sharing files with users, and updating other field values. 
  2. You can pass multiple comma-separated values from this custom field and split them in the trigger.
  3. You can perform various business logic based on the field values set from the file upload component.

I hope this was helpful. Let me know in the comments what different scenarios you have used this workaround for.


No comments :
Post a Comment

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com