How to fetch and show all the Notes for a record using Lightning Web Component in Salesforce?

How to fetch and show all the Notes for a record using Lightning Web Component in Salesforce?

Apex Class:

public with sharing class PrintNotesController {  
  
	@AuraEnabled( cacheable=true )    
	public static List < NoteWrapper > fetchNotes( String strRecordId )  {  
		  
		List < NoteWrapper > listNoteWrappers = new List < NoteWrapper >();  
		Set < Id > setDocIds = new Set < Id >();  
		for ( ContentDocumentLink objCDL : [ SELECT ContentDocumentId FROM ContentDocumentLink  WHERE LinkedEntityId =: strRecordId ] )  
			setDocIds.add( objCDL.ContentDocumentId );  
		for( ContentNote objNote : [ SELECT Title, Content, CreatedDate FROM ContentNote WHERE Id IN: setDocIds ORDER BY CreatedDate ] ) {  
  
			NoteWrapper objWrapper = new NoteWrapper();  
			objWrapper.strTitle = objNote.Title;  
			//Below replaceAll removes all the HTML tags from the Content  
			objWrapper.strNotes = objNote.Content.toString().replaceAll( '<[^>]+>',' ' );  
			objWrapper.strCreatedDate = String.valueOf( objNote.CreatedDate.date() );  
			listNoteWrappers.add( objWrapper );  
  
		}  
		return listNoteWrappers;  
  
	}  
  
	public class NoteWrapper {  
  
		@AuraEnabled  
		public String strTitle;  
		@AuraEnabled  
		public String strNotes;  
		@AuraEnabled  
		public String strCreatedDate;  
  
	}  
  
}  

Lighting Web Component HTML:

<template>  
	  
	<div class="slds-m-around_medium">    
  
		<div if:true={records.data}>    
  
			<template for:each={records.data} for:item="rec">   
				<b key={rec.Id}>{rec.strCreatedDate} - {rec.strTitle}</b><br key={rec.Id}/>  
				{rec.strNotes}<br key={rec.Id}/><br key={rec.Id}/>  
			</template>  
  
		</div>  
  
	</div>  
  
</template>  

Lighting Web Component JavaScript:

import { LightningElement,api,wire } from 'lwc';  
import fetchNotes from '@salesforce/apex/PrintNotesController.fetchNotes';  
  
export default class PrintNotesLWC extends LightningElement {  
  
	@api recId;      
	@wire(fetchNotes, { strRecordId: '$recId' })    
	records;   
  
}  

Lightning Web Component JavaScript meta.xml:

<?xml version="1.0" encoding="UTF-8"?>  
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="PrintNotesLWC">  
	<apiVersion>46.0</apiVersion>  
	<isExposed>false</isExposed>      
	<targets>    
		<target>lightning__RecordPage</target>    
	</targets>    
	<targetConfigs>    
		<targetConfig targets="lightning__RecordPage">    
			<property name="recId" type="String" label="Record Id" description="Record Id"/>    
		</targetConfig>  
	</targetConfigs>      
</LightningComponentBundle>  

Lightning Component:

<aura:component implements = "force:lightningQuickActionWithoutHeader,force:hasRecordId">  
    <c:printNotesLWC recId="{!v.recordId}"/>  
</aura:component>  

Output:

Leave a Reply