What is the correct way to pass Parameters to Lightning JS controller from UI:Button?
There is no need for a form
in your td
.
Wrap your button
in a div
, attach the value to the div
via a data-
attribute and grab it from the event.currentTarget
. Eg:
<div onclick="{!c.removeItem}" data-value="123">
<lightning:button label="Remove" iconName="utility:delete" iconPosition="left" variant="destructive" value="123"/>
</div>
Controller method:
removeItem: function(component, event, helper) {
var ctarget = event.currentTarget;
var id_str = ctarget.dataset.value;
console.log(id_str);
}
The alternative method is to define a new custom component for a row in the table. Make that component have Item as an attribute, then you can read it in the event handler.
<aura:component>
<aura:attribute name="item" type="Item__c" />
<tr>
<td>
<div class="slds-truncate" title="{!item.Name}">{!item.Name}</div>
</td>
<td>
<lightning:button label="Remove" iconName="utility:delete" iconPosition="left" variant="destructive" onclick="{!c.removeItem}" value="{!item.Id}"/>
</td>
</tr>
</aura:component>
Then the controller for this component would include:
removeItem: function(component, event, helper) {
var id_str = component.get('v.item').Id;
console.log(id_str);
}
I think currently recommended by Salesforce way of passing parameters from button to controller is by using event.getSource()
. Please note it will work only on Lightning components (for example on lightning:button
and not on standard HTML <button>
. For HTML components use event.currentTarget
as in other answer) Please consider following example:
Component
<aura:attribute name="colours" type="String[]" default="['red', 'green', 'blue']"/>
<aura:iteration items="{!v.colours}" var="col">
<lightning:button label="{!'Colour ' + col}" value="{!col}" onclick="{!c.onBtnColourClick}"/><br/>
</aura:iteration>
Controller
onBtnColourClick: function(component, event, helper) {
var msg = event.getSource().get('v.value');
//do something with value
component.set('v.message', msg);
},
This is especially useful in cases like when you need to make a table in which every row has individual button (let's say Delete the record from this row). We have to pass somehow the recordId
of record in specific row.
For lightning:button
component, you can use name
and value
attributes to assign value from iterated object.
WARNING:
Please note that as time of writing you cannot generate aura:id
dynamically, so in the example above writing aura:id="{!col}"
and using event.getSource().getLocalId()
in controller would give you literally '{!col}'
string!