Effortlessly Retrieve Related List Records in Salesforce LWC

by Zuber Rangreaz
0 comment

Hello friends, today we are going to discuss Effortlessly Retrieve Related List Records in Salesforce LWC. The getRelatedListRecords wire adapter is used to fetch records from related lists in Salesforce. Related lists display details and links to records associated with a specific parent record, such as contacts, cases, notes, or files related to an account.

Get-Related-List-Records-in-LWC-Salesforce

Also, check this: Toast Message Container in Lightning Web Component Salesforce 

Key Highlights :

  1. @api decorator: Makes the recordId property public, allowing it to be set from outside the component.
  2. getRelatedListRecords wire adapter: Fetches related list records. Parameters include:
  3. parentRecordId ID of the parent record.
  4. relatedListId API name of the related list (e.g., ‘Contacts’).
  5. wiredRelatedListRecords function: Processes the data or error returned by the wire adapter.
  6. fields: Specifies which fields to retrieve from the related records.

Code :

Import This Line…

import { getRelatedListRecords } from 'lightning/uiRelatedListApi';

AccountWithContactsController.cls:

public with sharing class AccountWithContactsController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountsWithContacts() {
        return [
            SELECT Id, Name 
            FROM Account 
            WHERE Id IN (SELECT AccountId FROM Contact)
            ORDER BY CreatedDate DESC
        LIMIT 10];
    }
}

getRelatedListRecord.html:

<template>
	<lightning-card title="Account Selector" icon-name="standard:account">
		<div class="slds-p-around_medium">
			<lightning-combobox name="accountPicklist" label="Select Account" placeholder="Select an Account"
				options={accountOptions} onchange={handleChange}>
			</lightning-combobox>
		</div>
	</lightning-card>
	<br/>
	<lightning-card title="Related Contact" icon-name="standard:contact">
		<template lwc:if={showContact}>
			<lightning-datatable key-field="Id" data={contact} columns={contactColumns}>
			</lightning-datatable>
		</template>
		<template lwc:else>
			<p class="slds-p-left_medium">No Contact records to display.</p>
		</template>
	</lightning-card>
</template>

getRelatedListRecord.js:

import { LightningElement, track, wire } from 'lwc';
import getAccountsWithContacts from '@salesforce/apex/AccountWithContactsController.getAccountsWithContacts';
import { getRelatedListRecords } from 'lightning/uiRelatedListApi';

export default class getRelatedListRecord extends LightningElement {
    @track accountOptions = [];
    selectedAccountId;
    contact = [];
    showContact = false;

    @track contactColumns = [
        { label: 'Name', fieldName: 'Name', type: 'text' },
        { label: 'Last Name', fieldName: 'LastName', type: 'text' },
        { label: 'Email', fieldName: 'Email', type: 'email' },
        { label: 'Phone', fieldName: 'Phone', type: 'phone' },
    ];

    @wire(getAccountsWithContacts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.accountOptions = data.map(account => {
                return { label: account.Name, value: account.Id };
            });
        } else if (error) {
            console.error('Error fetching accounts', error);
        }
    }

    @wire(getRelatedListRecords, {
        parentRecordId: '$selectedAccountId',
        relatedListId: 'Contacts',
        fields: ['Contact.Name', 'Contact.Id', 'Contact.LastName', 'Contact.Email', 'Contact.Phone'],
        sortBy: ['Contact.Name']
    })

    wiredContact({ data, error }) {
        if (data) {
            this.contact = data.records.map(record => {
                return {
                    Id: record.fields.Id.value,
                    Name: record.fields.Name.value,
                    LastName: record.fields.LastName.value,
                    Email: record.fields.Email.value,
                    Phone: record.fields.Phone.value,
                };
            });
            this.showContact = this.contact.length > 0;
        }
        if (error) {
            console.error('Error occurred retrieving Contact records', error);
        }
    }

    handleChange(event) {
        this.selectedAccountId = event.detail.value;
        console.log('Selected Account Id:', this.selectedAccountId);
    }
}

Output :

Reference :

  1. UI Related List API
What’s your Reaction?
+1
3
+1
0
+1
1
+1
0
+1
0
+1
0

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.