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:

Wednesday, September 25, 2019

System.QueryException: Non-selective query against large object type (more than 200000 rows)

Always try to use WHERE clause to query results, this limits down the number of records getting fetched and thus avoid this error.

Best practice - use indexed fields in WHERE clause.