Sunday, September 29, 2019

Preview Files/Attachments in Lightning Web Components (LWCs)

--------------------- TestClass.cls --------------------------

//to fetch all files in an org
@AuraEnabled(cacheable=true)
public static List<ContentDocumentLink> getFiles(){
    return [Select Id, ContentDocumentId From ContentDocumentLink];
}

//to fetch files related to a specific record
@AuraEnabled(cacheable=true)
public static List<ContentDocumentLink> getFilesFromSpecificRecord(sObject sObjId){
    return [Select Id, ContentDocumentId From ContentDocumentLink WHERE LinkedEntityId =:sObjId];
}

------------------- fetchFilesFromOrg.js -----------------
/* eslint-disable no-console */
/* eslint-disable no-unused-vars */

import { LightningElement, track , wire} from 'lwc';
import { NavigationMixin, CurrentPageReference } from 'lightning/navigation';
import getFiles from '@salesforce/apex/TestClass.getFiles';

export default class fetchFilesFromOrg extends NavigationMixin(LightningElement) {
@track data;
        @wire(getFiles,{})
        rec({error,data}){
         if(data){
            var result =[];
            for(var i=0; i<data.length; i++){
                result.push(data[i].ContentDocumentId);
            }
            this.data=result;
         }if(error){
             console.log("error while fetching files from org");
         }
        }

navigateToWebPage(event) {
var fileId = event.target.title;
this[NavigationMixin.Navigate]({
                type: 'standard__namedPage',
                attributes: {
                    pageName: 'filePreview'
                },
                state : {
                   selectedRecordId: fileId
                }
              })
}
}
}

------------------ fetchFilesFromOrg.html -----------------------

<template>
<lightning-card>

<template for:each={data} for:item='item'>
<tr key={item.Id}>
<td><a> <lightning-formatted-rich-text  title={item} value={item} onclick={navigateToWebPage}></lightning-formatted-rich-text> </a></td>
</tr>
    </template>

</lightning-card>
</template>

This shows up like this:

No comments:

Post a Comment