Salesforce

Iterating through a list with Open Details Button

One of the main point about iterating through a list is there is an action at the end – for instance opening a record.  So each row in a data table might need a button but we need to know what recordId to open.

It turns out there is a fairly easy way to do this.

Start with a new lightnign component and hook it up to an Apex controller and then we have some code to do a fairly standard data table:


<aura:component implements="flexipage:availableForAllPageTypes" Controller="Travel" access="global" >
<aura:attribute name="travels" type="Travel__c[]"/>
<aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
<lightning:card title="Standard List" iconName="standard:report">
<table class="slds-table slds-table_bordered slds-table_cell-buffer">
<thead>
<tr class="slds-text-title_caps">
<th scope="col">
<div class="slds-truncate" title="col1">Name</div>
</th>
<th scope="col">
<div class="slds-truncate" title="col2">Country</div>
</th>
<th scope="col">
<div class="slds-truncate" title="col3">Action</div>
</th>
</tr>
</thead>
<tbody>
<aura:iteration items="{!v.travels}" var="travel">
<tr>
<th scope="row" data-label="Name">
<div class="slds-truncate">{!travel.Name}</div>
</th>
<td data-label="Coountry">
<div class="slds-truncate">{!travel.Countries__c}</div>
</td>
<td data-label="Open">
<div class="slds-truncate">Open</div>
</td>
</tr>
</aura:iteration>
</tbody>
</table>
</lightning:card>
</aura:component>

Controller code


({
doInit: function(component, event, helper) {
var action = component.get("c.getTravel");
action.setCallback(this, function(response) {
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.travels", response.getReturnValue());
}
else {
console.log("Failed with state: " + state);
}
});
$A.enqueueAction(action);
},
})

 


public with sharing class Travel {
@AuraEnabled
public static List<Travel__c> getTravel() {
return [SELECT Id, Name, Countries__c
FROM Travel__c];
}
}

 

This should give something along these lines (obviously the data and columns will be different).   We have an Open tag but this needs to be replaced with a button and then an action to capture the specific row.

 

Add a button in place of the Open text;


<lightning:button onclick="{! c.openRecord }" name="{!travel.Id}" label="Open Record"/>

Now we need to have the openRecord in the controller and look up the name to get the Id and then do a e.force:navigateToSObject to open the record:


openRecord: function (component, event, helper) {
var id = event.getSource().get("v.name");
console.log(id);
var navEvt = $A.get("e.force:navigateToSObject");
navEvt.setParams({
"recordId": id,
});
navEvt.fire();
},

Leave a Reply

Your email address will not be published. Required fields are marked *