[SalesForce] How to know which button was clicked

I'm now learning Lightning and trying to build some simple app.

I followed this answer to get navigation between views. And in my component(foo) I got the following:

<aura:attribute name="myObjects" type="ak90.myObject__c[]"/>
<aura:attribute name="objId" type="String" />
//some code ...
<aura:iteration items="{!v.myObjects}" var="obj">
    <div>
        <ui:button label="{!obj.ak90__Name__c}" aura:id="{!obj.Id}" press="{!c.navToBar}"/>
    </div>
</aura:iteration>

And depending on which button was clicked I want to set objId attribute to Id of that record so that I can pass it to the next view that should load more detailed view of that record.

Best Answer

I feel like there should be a better solution, but one way to achieve what you're trying to do is to create a separate component to put inside your aura:iteration.

So, let's say you edit your aura:iteration to look like this:

<aura:iteration items="{!v.myObjects}" var="obj">
    <ak90:objectListItem item="{!obj}"/>
</aura:iteration>

And you create an objectListItem component that looks like this:

<!-- Attribute definition(s) -->
<aura:attribute name="item" type="ak90.myObject__c"/>

<!-- UI element(s) -->
<div>
    <ui:button label="{!item.ak90__Name__c}" aura:id="{!item.Id}" press="{!c.navToBar}"/>
</div>

In your c.navToBar() function, you'll be able to use component.get("v.item.Id") to figure out which specific button was pressed. From there, you can fire an event that includes the specific Salesforce ID corresponding to the pressed button, and then do what you need from there.

Related Topic