How can I use the “for each” loop in IWC for iterating records?

33    Asked by DavidWHITE in Salesforce , Asked on Apr 9, 2024

 I am currently developing custom widgets in salesforce interactions widget customization and for this particular task I need to iterate over a list of records that are retrieved from an apex controller by using the @AuraEnabled annotations. How can I use the “for each” loop in IWC for iterating these records? 

Answered by Connor Peake

 In the context of Salesforce, here is how you can use the “for each” loop for iterating over a list of records that are retrieved from an apex controller:-

Firstly, you would need to define an apex method in your particular Apex controller with the @AuraEnabled annotations for retrieving the list of records that you want to be retrieved.

In your HTML template now you can use the “for each” loop for iterating over the records array and also can display more details as needed.

Here is an example given:-

Apex controller (Mycontroller.cls)
Public with sharing class MyController {
    // Apex method to retrieve records
    @AuraEnabled(cacheable=true)
    Public static List getRecords() {
        // Query and return a list of MyObject__c records
        Return [SELECT Id, Name, Field1__c, Field2__c FROM MyObject__c LIMIT 10];
    }
}
JavaScript file(mycustomwidget.js)
Import { LightningElement, wire } from ‘lwc’;
Import getRecords from ‘@salesforce/apex/MyController.getRecords’;
Export default class MyCustomWidget extends LightningElement {
    Records; // Property to store retrieved records
    // Wire a function to fetch records from the Apex controller when the component is initialized
    @wire(getRecords)
    wiredRecords({ error, data }) {
        if (data) {
            this.records = data; // Assign the retrieved records to the ‘records’ property
        } else if (error) {
            Console.error(‘Error fetching records:’, error);
        }
    }
}
HTML template (mycustomwidget.html)

       
   

CSS file (mycustomwidget.css)
.container {
    Font-family: Arial, sans-serif;
    Padding: 10px;
}
.container h2 {
    Margin-bottom: 10px;
}
Ul {
    List-style-type: none;
    Padding: 0;
}
Li {
    Padding: 10px;
}
.even {
    Background-color: #f0f0f0; /* Light gray background for even rows */
}
.odd {
    Background-color: #ffffff; /* White background for odd rows */
}

Your Answer

Interviews

Parent Categories