Below is my code for Lightning Web Component:

HTML File:

    <template if:true = {files.data}>
        <template for:each={files.data} for:item='file'>
            <lightning-card key={recordId} icon-name={file.Title}></lightning-card>

    <template if:true={error}>

        <c-error-panel errors={error}></c-error-panel>



JS FIle:

import { LightningElement, wire, track, api } from 'lwc';

import getAllRelatedAttachments from '@salesforce/apex/filesWebComponentController.getAllRelatedAttachments';

export default class lightning  extends LightningElement {
    @track files={data:[]};
    @track error;
    @api recordId;

    @wire (getAllRelatedAttachments,{recordId:"$recordId"})

            if (data) {
                this.files = data;
                this.error = undefined;
            } else if (error) {
                this.error = error;
                this.files = undefined;


My Apex Controller:

public with sharing class filesWebComponentController {
    public filesWebComponentController() {

public static List<ContentVersion> getAllRelatedAttachments(Id recordId){
set<id> parentIDs=new set<id>();
List<Contact> conList = [select Id From Contact where id=:recordId];
    for(Contact con:conList){
    List<ContentDocumentLink> files = [SELECT ContentDocumentId, LinkedEntityId FROM ContentDocumentLink WHERE LinkedEntityId IN :parentIDs];
        List<ID> fileIds = new List<ID>();
        for (ContentDocumentLink docLink : files){

     if(!fileIds.isEmpty()) {
            List<ContentVersion> file =  [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE ContentDocumentId IN :fileIds];
            return file;
        return Null;


  • For multi-line code blocks, prefix each line with four spaces. Alternatively, highlight the code and use the {} button in the editor. For inline code, use the backtick (" ` ") character. – sfdcfox Jan 24 at 4:23

If files is undefined, you get an error in the template (you do so here when there's an error). Instead, just check to see if it has a value:

<template if:true={files}>

Also, arguably, you shouldn't return "null" when there's no records; that will show an error when no error actually occurred. Your error panel will probably give errors itself in that scenario.

//if(!fileIds.isEmpty()) {
  return [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE ContentDocumentId IN :fileIds];
    //return Null;

Also, you'll get an additional error if your method returns a null value and is cacheable, so again, an empty list is the correct response.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.