function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Manu KM 9Manu KM 9 

Need to pass parameters to lightning-controller on Button click in Lightning Component


Hi,

Lets say we have an object and on the lightning component we are displaying its details. when ever i click on the button i need to pass record id to the controller.

This how my code look like:-
<aura:iteration items="{! v.vegs}" var="veg">
            <div class='tile' aura:id="test1" press="{! c.tester}" >              
                <img src='{! veg.Image__c}'  onClick="{! c.tester}" aura:id="imgId" value="{! veg.Name }"> </img>
                Name: {! veg.Name } <br></br>             
                price: {! veg.Price__c }   <br></br>
                <ui:button label="Add to cart" press="{! c.addToCart}"  aura:id="btn1" >      </ui:button>               
           </div>
</aura:iteration>

I want something similer to :-
 
<aura:iteration items="{!v.newCases}" var="case">
<button type="button" onclick="{!c.showCaseDeleteModal(case.Id)}">Delete</button>
</aura:iteration>


How can I pass the id to a component controller when the  button gets clicked?


Thank you!
Best Answer chosen by Manu KM 9
Veenesh VikramVeenesh Vikram
You can get ID in the JS controller directly, no need to assign to another attribute,

Do like this:
In your component, assign the record Id to the button's Id
<aura:iteration items="{!v.newCases}" var="case">  
<button type="button" onclick="{!c.showCaseDeleteModal}" id={!case.Id}>Delete</button> 
</aura:iteration>
In your JS controller, capture the ID as as source of event:
 
showCaseDeleteModal: function(component, event, helper) {
var idx = event.target.id;
alert(idx);                       //here is your ID
});

Kindly mark as solved if it helps.

Regards
Veenesh

All Answers

Srinivas SSrinivas S
1. Please pass the caseId to a attribute in the lightning component.
2.  In js controller/helper we can access 'component' from which we can fetch the attribute value.

------------
Thanks,
Srinivas
- Please mark as solution if your problem is resolved.
Veenesh VikramVeenesh Vikram
You can get ID in the JS controller directly, no need to assign to another attribute,

Do like this:
In your component, assign the record Id to the button's Id
<aura:iteration items="{!v.newCases}" var="case">  
<button type="button" onclick="{!c.showCaseDeleteModal}" id={!case.Id}>Delete</button> 
</aura:iteration>
In your JS controller, capture the ID as as source of event:
 
showCaseDeleteModal: function(component, event, helper) {
var idx = event.target.id;
alert(idx);                       //here is your ID
});

Kindly mark as solved if it helps.

Regards
Veenesh
This was selected as the best answer
Devendra SaranDevendra Saran
your provided solution is not working AT ALL! @veenesh
BlindsydeBlindsyde
Worked for me thank you! 
<button type="button" onclick="{!c.toggleProduct}" id="{!product.ProductId + '_toggleBtn'}">Toggle</button>
NishantBansalNishantBansal
Another solution to pass information from Lightning component view to Lightning component controller,

Component:
<aura:iteration items="{!v.newCases}" var="case">
<button type="button" onclick="{!c.showCaseDeleteModal}"  data-caseID ="{!case.Id}">Delete</button>
</aura:iteration>

Controller:
var caseID = event.currentTarget.dataset.caseID;
alert(caseID);

This should work, and in similar way we can add and pass multiple attributes.

Hit thumbs up, if this works for you.
Meenakshi Rajasekaran 7Meenakshi Rajasekaran 7
I know its a very old thread.But I am stuck with a similiar issue but requirement is that i need to navigate to the record detail page when i click on the button. Here is  my code..Plzz help!

​Budget-Master object; Expense-detail object

Budgetdisplay.cmp
<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable" controller="budgetlightningcntrl" >
    <aura:attribute name="expense" type="Expenses__c[]"/>
    <aura:attribute name="spinner" type="Boolean" default="false"/>
    <aura:handler event="aura:waiting" action="{!c.showSpinner}"/>    
    <aura:handler event="aura:doneWaiting" action="{!c.hideSpinner}"/>     
  <aura:handler event="force:navigateToSObject" action="{!c.navigate}"/>   
   <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>
    
  <aura:if isTrue="{!v.spinner}">
    <div aura:id="spinnerId" class="slds-spinner_container">
       <div class="slds-spinner--brand  slds-spinner slds-spinner--large slds-is-relative" role="alert">
         <span class="slds-assistive-text">Loading</span>
         <div class="slds-spinner__dot-a"></div>
         <div class="slds-spinner__dot-b"></div>
       </div>
    </div>
 </aura:if>
        
    <table class="slds-p-around_x-small slds-text-body_small slds-table slds-table--bordered slds-table--fixed-layout " >
                <thead>
                    <tr>                        
                        <th scope="col" colspan="3" class="slds-truncate slds-text-align--center slds-text-align--center 
                                                           slds-text-align_right slds-text-heading_medium">My Budget and Expenses</th>
                    </tr>
                    <tr>                        
                        <th scope="col"><div class="slds-truncate ">My Budget</div></th>
                        <th scope="col" ><div class=" slds-text-align--center">Expenses ID</div></th>
                        <th scope="col"><div class="slds-truncate  slds-text-align--right">Amount</div></th>
                        <th scope="col"><div class="slds-truncate  slds-text-align--right">Status</div></th>
                        <th scope="col"><div class="slds-truncate  slds-text-align--right">Mode of Travel</div></th>
                        <th scope="col"><div class="slds-truncate  slds-text-align--right">Date of Expense</div></th>
                    </tr>
                </thead> 
        <tbody>
            <aura:iteration items="{!v.expense}" var="e">
                <tr class="slds-hint-parent" >
                    <td>
                        <button type="button" onclick="{!c.navigate}" id="{!e.Budget__r.Id}">check Budget</button>                      
                            </td>
                            <td scope="row">
                                <div class="slds-truncate slds-text-align--right" >
                                <a target="_blank" href="{!'/'+e.Id}">{!e.Name}</a>                                 
                                </div>
                                </td>
                            <td scope="row">
                                 <div class="slds-truncate slds-text-align--right"><ui:outputNumber value="{!e.Amount__c}"/></div>
                            </td>
                            <td scope="row">
                                <div class="slds-truncate slds-text-align--right"><ui:outputText value="{!e.Status__c}" /></div>                            
                            </td>
                            <td scope="row">
                                <div class="slds-truncate slds-text-align--right"><ui:outputText value="{!e.Mode_of_Travel__c}"/></div>
                            </td>  
                            <td scope="row">
                                <div class="slds-truncate slds-text-align--right"><ui:outputDate value="{!e.Date_of_Expense__c}"/></div>
                            </td>
                        </tr>            
            </aura:iteration>
          </tbody>
       </table>
</aura:component>

Budgetdisplaycontroller.js
({
    doInit: function(component, event, helper) {

    // Create the action
    var action = component.get("c.getexpense");

    // Add callback behavior for when response is received
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (component.isValid() && state === "SUCCESS") {
            component.set("v.expense", response.getReturnValue());
        }
        else {
            console.log("Failed with state: " + state);
        }
    });

    // Send action off to be executed
    $A.enqueueAction(action);
},

    navigate: function(component, event, helper) {
   var idx = event.target.id;
           alert(idx);   

}
,
    showSpinner: function(component,event,helper){
        component.set("v.spinner",true);
    },
    
    hideSpinner: function(component,event,helper){
        component.set("v.spinner",false);
    }
    
})

 
Chuck H.Chuck H.
For those still facing this problem, I've had success with the following configuration:

Component code:
<aura:iteration aura:id="delRows" items="{!v.delRows}" var="row2" indexVar="i">

 //the row2 car here refers to the itteration var established on line 1 of this snippet 

<lightning:button aura:id="{!row2.rowId}" name="{!row2.rowId}" label="SHOW" onclick="{!c.unhideThis}"/> 

</aura:iteration>


Controller code:
unhideThis : function(component, event, helper){ 

 console.log(event.getSource().get("v.name")); 

 }

 
Nestor VelázquezNestor Velázquez
@Veenesh Vikram Hi, I try to pass this values to my controller (Apex class) for create filter or make inserts or updates, but nothing, what is the next step. 
Pierre-Alain THIOUT 4Pierre-Alain THIOUT 4
For those who are still facing the issue in 2018 :

In the component
 
<div onclick="{!c.myFunction}" data-myvalue="this is it">
click me
</div>

And in the JS Controller
 
myFunction : function (component, event, helper) {
    var component_target = event.currentTarget;
    var attribute = component_target.dataset.myvalue;
    console.info(attribute);
}

It feels like there are lots of small "details" that makes developping lighning / Apex components quite painful.

Regards.
 
David Roberts 4David Roberts 4
Thanks Chuck,

Solved it for me. I use a wrapper to hold the contact details and other info.

<aura:iteration var="varContactWrapper" items="{!v.contactWrapperList}"> 

<lightning:button
       variant="neutral"
       label="Cancel"
       onclick="{!c.handleCancel}"
       aura:id="{!varContactWrapper}"
       name="{!varContactWrapper}">
</lightning:button>     


handleCancel : function (component, event, helper) {
        var contactToGo = event.getSource().get("v.name");
        console.log('contactToGo '+contactToGo.cont.Name);
        ...etc...
}//handleCancel
Nestor VelázquezNestor Velázquez
Only use . . . force:hasRecordId and handle in the controller with component.get
<aura:component controller="controller" 
                implements="flexipage:availableForAllPageTypes,force:hasRecordId" access="global">
 
var recordId = component.get("v.recordId");

 
David Roberts 4David Roberts 4
Hi Nestor,
What you suggest works for the simple case of the calling component's recordId but, if you want to send more, then the above aura:id and name is the solution.
Regards,
Dave.
Nestor VelázquezNestor Velázquez
oh! Yes, you're right: 
 
In cmp 

<aura:attribute name="theFormObject" type="CustomObject__c" default="{ 'sobjectType': 'theObject__c',                 'Field1__c': '', 'Field2__c': '' }"/> 

<form class="slds-form--stacked"> 
<lightning:input aura:id="theForm" label="Field 1: " value="{!v.theFormObject.Field1__c}" /> 
<lightning:input aura:id="theForm" label="Field 2: " value="{!v.theFormObject.Field2__c}" /> 
</form>
 
In controller 

var data     = component.get("v.theFormObject"); 
var value1 = data.Field1; 
var value2 = data.Field2;



 
Kimber lyyKimber lyy
Thanks for sharing valuable scripts, Thanks again developers (https://www.discogs.com/user/kimberlyy555)
David Roberts 4David Roberts 4
Explanation at: https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/lightning_base_events.htm
The simplest form in Lightning is:
<lightning:button variant="brand" label="Send some data" onclick="{!c.myfunction}" name="my Data"/>
and controller:
myfunction: function (component, event, helper) {
    var param = event.getSource().get("v.name");
    console.info('parameter '+param);
},
David Roberts 4David Roberts 4
I had cause to revisit this and found this solution works:
<aura:iteration items="{!v.myitems}" var="obj" indexVar= "idx">
   <lightning:buttonIcon iconName="utility:like"  Title="Click to like" alternativeText="Like"
                                               onclick="{!c.likeThisOne}" name="{!idx}" />
</aura:iteration>

and the controller:
likeThisOne : function (component, event, helper){
      var index = event.getSource().get("v.name");
        var theItems = component.get('v.myitems');
        var likethisone = theItems[index];
        
    },//likeThisOne

The indexVar is passed in using the name attribute. It can then be used to index the object list.​​​​​​​