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
sheila srivatsavsheila srivatsav 

radio button for each contact record in lightning component

My requirement is to display contact records so for every contact record displayed I need a radio button beside it.

I have done like so far.
@AuraEnabled
    Public static List<Contact> showContacts()
    {
      List<Contact> conList = [select Id,Name
                                 FROM 
                                 contact
                                 Order By name LIMIT 15];
        return conList;
    }

<aura:component implements="flexipage:availableForAllPageTypes" 
                controller="MyController"
                access="global" >
	
    <aura:attribute name="contacts"
                    type="List[]"
                    access="global"/>
    
    <aura:handler name="init"
                  value="{!this}"
                  action="{!c.doInit}"/>
    
    
    <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="ContactName">Name</div>
                </th>
                
            </tr>
        </thead>
        
        <!--table body start, 
        Iterate contact list as a <tr> 
        -->
        <tbody>
            <aura:iteration items="{!v.contacts}" 
                            var="con">
                <tr>
                    <th scope="row">
                          <ui:inputRadio label="{!v.con}" change="{!c.onRadioChange}" />
                        <div class="slds-truncate" title="{!con.Name}">{!con.Name}</div>
                   </th>
                </tr>
            </aura:iteration>
           
        </tbody>
        
    </table>
    
</aura:component>

({
	doInit : function(component, event, helper) {
        helper.queryContacts(component,event,helper);
		
	},
    
    onRadioChange : function(component, event, helper) {
         // var selected = event.getSource().get("v.con");
        //alert(selected);
      }
})

({
	queryContacts : function(component,event,helper) {
		
        var action=component.get('c.showContacts');
        
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                
                component.set("v.contacts", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);

	}
})

<aura:application extends="force:slds"
                  access="global">
    
    <c:RadioButtons/>
    
</aura:application>
I am able to display radio button for every contact name but I am able to select multiple records.
I need to fire the change event when I select one contact record.

also other than <ui:radiobutton> what other component can we use?
thanks
sheila
 
Khan AnasKhan Anas (Salesforce Developers) 
Hi Sheila,

Greetings to you!

You can use lightning:datatable to display radio buttons. Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Component:
<aura:component controller="DataTableTestC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <!-- attributes -->
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="selectedRowsCount" type="Integer" default="0"/>
    <aura:attribute name="maxRowSelection" type="Integer" default="5"/>
    <aura:attribute name="isButtonDisabled" type="Boolean" default="true" access="PRIVATE"/>

    <!-- handlers-->
    <aura:handler name="init" value="{! this }" action="{! c.init }"/>

    <!-- the container element determine the height of the datatable -->
    <div style="height: 300px">
        <lightning:datatable
            columns="{! v.columns }"
            data="{! v.data }"
            keyField="id"
            maxRowSelection="{! v.maxRowSelection }"
            onrowselection="{! c.updateSelectedText }"/>
    </div>
</aura:component>

Controller:
({
    init: function (component, event, helper) {
        component.set('v.columns', [
            {label: 'Opp Name', fieldName: 'Name', editable: true, type: 'text'},
            {label: 'Acc Name', fieldName: 'AccountName', type: 'text'},
            {label: 'StageName', fieldName: 'StageName', editable: true, type: 'text'},
            {label: 'CloseDate', fieldName: 'CloseDate', type: 'date'},
            {label: 'Amount', fieldName: 'Amount', type: 'currency', cellAttributes: { alignment: 'left' }},
        ]);
            
            
        var action=component.get('c.getOpportunities');
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var rows = response.getReturnValue();
                for (var i = 0; i < rows.length; i++) {
                    var row = rows[i];
                    if (row.Account) row.AccountName = row.Account.Name;
                }
                component.set("v.data", rows);
                
            }
        });
        $A.enqueueAction(action);    

		component.set('v.maxRowSelection', 1);
        component.set('v.isButtonDisabled', true);
    },
        
        updateSelectedText: function (cmp, event) {
        var selectedRows = event.getParam('selectedRows');
        cmp.set('v.selectedRowsCount', selectedRows.length);
    },
})

Apex:
public class DataTableTestC {
    
    @AuraEnabled
    public static List<Opportunity> getOpportunities()
    {
        List<Opportunity> oppList=new List<Opportunity>();
        
        oppList=[select name,Account.Name,StageName,CloseDate,Amount from Opportunity
                 where StageName != NULL
                 AND
                 Amount != NULL
                 order by Account.Name];
        
        return oppList;
    }
    
}

If you want to use SLDS data table then I suggest please refer to the below links which might help you further.

https://techevangel.com/2018/05/06/lightning-datatable-with-single-checkbox-selection/

https://developer.salesforce.com/forums/?id=9060G0000005b0nQAA

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Twinkle Garg 15Twinkle Garg 15
Use the maxRowSelection="1" as an attribute in lightning datatable. It would automatically get converted to radio button.