Get Selected Record Id from Custom Iteration in Lightning Web Component

A very common use-case in Lightning Web Component is iterating a list over an array in HTML file using for:each or iterator directive. Many times as a developer, we have to do something on the items based on user interaction. You would definitely require to get selected record id from custom iteration. Let’s see an working example:-

Problem Statement

You have to iterate over a list of contact records and show the contact names as list. The business wants to have a button to navigate to the contact record page in Salesforce on onclick of it.

Solution

We are going to build a Lightning Web Component to fetch contact list and iterate using for:each directive. Let’s create a Lightning Web Component with name renderList in your visual studio code.

renderList.html

The html file has a lightning card and for:each directive to iterate. We are using lightning-layout to show contact name and buttons to navigate. We have two buttons for each row. One of them has name attribute and another one has data attribute. Those attribute has been assigned with record id of the record.

<template>
    <lightning-card title="HelloForEach" icon-name="custom:custom14">
        <ul class="slds-m-around_medium">
            <template for:each={contacts} for:item="contact">
                <lightning-layout multiple-rows key={contact.Id}>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="4" large-device-size="4" padding="around-small">
                        {contact.Name}
                    </lightning-layout-item>
                    <lightning-layout-item size="12" small-device-size="6" medium-device-size="4" large-device-size="4" padding="around-small">
                        <lightning-button name={contact.Id} label="Navigate - Approach 1" onclick={handleNavigateByNameAttribute}></lightning-button>
                        <lightning-button data-id={contact.Id} label="Navigate - Approach 1" onclick={handleNavigateByDataAttribute}></lightning-button>
                    </lightning-layout-item>
                </lightning-layout>
            </template>
        </ul>
    </lightning-card>
</template>

renderList.js

The JavaScript file imports NavigationMixin module and the apex method. It has connectedCallback to call the apex method and assign the returned value to a property. The two handlers which demonstrate the way to get id of the selected row and navigate to the record.

Approach 1 – We access the value of selected record id using event.target.name.Check handleNavigateByNameAttribute method.

Approach 2 – We access the value of selected record id using event.target.dataset.id as the name of data attribute was data-id. Check handleNavigateByDataAttribute method.

import { LightningElement } from 'lwc';
import fetchContact from '@salesforce/apex/ContactController.fetchContact';
import { NavigationMixin } from 'lightning/navigation';
export default class CustomIteration extends NavigationMixin(LightningElement) {
    contacts;
    error;
    connectedCallback(){
        fetchContact({}).then(result => {
            this.contacts = result;
        }).catch(error => {
            this.error = error;
        });
    }
    handleNavigateByNameAttribute(event){
        //getting record id using name attribute
        const selectedRecordId = event.target.name;
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: selectedRecordId,
                objectApiName: 'Contact', // objectApiName is optional
                actionName: 'view'
            }
        });
    }
    handleNavigateByDataAttribute(event){
        //getting record id using using data-attributes
        const selectedRecordId = event.target.dataset.id;
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: selectedRecordId,
                objectApiName: 'Contact', // objectApiName is optional
                actionName: 'view'
            }
        });
    }

}

customIteration.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

We have apex controller as well. The name of apex class is ContactController. Create the apex class with the same name and paste the below code.

public with sharing class ContactController {
    @AuraEnabled
    public static List<Contact> fetchContact(){
        try {
            List<Contact> contactList = new List<Contact>();
            contactList = [select id, Name from Contact order by Name ASC limit 10];
            return contactList;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

DemoGet Selected Record Id from Custom Iteration

Leave a Reply