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
Ravish Verma 15Ravish Verma 15 

How to display picklist values as radio buttons in lightning edit record

Hi,
I am using a lightning edit record control and I want to display picklist values as radio buttons and selected picklist value in the backend should display, selected radio buttons. Is it possible using lightning editrecord and any other way to acheive this ? any help will be much appriciated.

Thanks 
Ravish
Best Answer chosen by Ravish Verma 15
Khan AnasKhan Anas (Salesforce Developers) 
Hi Ravish,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Apex:
public class SampleController {
    
    @AuraEnabled //Save Account Data
    Public static void createAccount(Account objacc){
        try{
            //Insert Account Record
            insert objacc; 
            
        }catch(Exception e){
            //throw exception message
            throw new AuraHandledException(e.getMessage());
        }
        finally {
        }
    }
    
    @AuraEnabled //get Account Industry Picklist Values
    public static Map<String, String> getIndustry(){
        Map<String, String> options = new Map<String, String>();
        //get Account Industry Field Describe
        Schema.DescribeFieldResult fieldResult = Account.Industry.getDescribe();
        //get Account Industry Picklist Values
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry p: pList) {
            //Put Picklist Value & Label in Map
            options.put(p.getValue(), p.getLabel());
        }
        return options;
    }
}

Component:
<!--Sample.cmp-->
<aura:component controller="SampleController" implements="flexipage:availableForAllPageTypes,force:appHostable">
    
    <!--Declare Attributes-->
    <aura:attribute name="industryMap" type="Map"/>
    <aura:attribute name="acc" type="Account" default="{'sobjectType':'Account', 
                                                       'Name': '',
                                                       'AccountNumber': '',
                                                       'Email': '',
                                                       'Phone': '', 
                                                       'Industry': ''}"/>
    
    <!--Declare Handler-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
    
    <!--Component Start-->
    <div class="slds-m-around--xx-large">
        <div class="container-fluid">
            <div class="form-group">
                <lightning:input name="accName" type="text" required="true" maxlength="50" label="Account Name" value="{!v.acc.Name}" />
            </div>
            <div class="form-group">
                <lightning:input name="accNumber" type="text" required="true" maxlength="10" label="Account Number" value="{!v.acc.AccountNumber}" />
            </div>
            <div class="form-group">
                <lightning:input name="accEmail" type="email" required="true" maxlength="100" label="Email" value="{!v.acc.Email}" />
            </div>
            <div class="form-group">
                <lightning:input name="accPhone" type="phone" required="true" maxlength="10" label="Phone" value="{!v.acc.Phone}" />
            </div>
            <div class="form-group">
                <!--Lightning radio group component-->
                <lightning:radioGroup name="radioGroup"
                                      label="Industry"
                                      required="true"
                                      options="{!v.industryMap}"
                                      value="{!v.acc.Industry}"
                                      type="radio"/>
            </div>
        </div>
        <br/>
        <lightning:button variant="brand" label="Submit" onclick="{!c.handleAccountSave}" />              
    </div>
    <!--Component End-->
</aura:component>

Controller:
({
    //Load Account Industry Picklist
    doInit: function(component, event, helper) {        
        helper.getIndustryPicklist(component, event);
    },
    
    //handle Account Save
    handleAccountSave : function(component, event, helper) {
        helper.saveAccount(component, event);
    },
    
    //handle Industry Picklist Selection
    handleCompanyOnChange : function(component, event, helper) {
        var indutry = component.get("v.acc.Industry");
        alert(indutry);
    }
})

Helper:
({
    //get Industry Picklist Value
    getIndustryPicklist: function(component, event) {
        var action = component.get("c.getIndustry");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                var industryMap = [];
                for(var key in result){
                    industryMap.push({label: result[key], value: key});
                }
                component.set("v.industryMap", industryMap);
            }
        });
        $A.enqueueAction(action);
    },
    
    //handle Account Save
    saveAccount : function(component, event) {
        var acc = component.get("v.acc");
        var action = component.get("c.createAccount");
        action.setParams({
            objacc : acc
        });
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                alert('Record is Created Successfully');
            } else if(state === "ERROR"){
                var errors = action.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert(errors[0].message);
                    }
                }
            }else if (status === "INCOMPLETE") {
                alert('No response from server or client is offline.');
            }
        });       
        $A.enqueueAction(action);
    }
})

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

All Answers

Khan AnasKhan Anas (Salesforce Developers) 
Hi Ravish,

Greetings to you!

Please try the below code, I have tested in my org and it is working fine. Kindly modify the code as per your requirement.

Apex:
public class SampleController {
    
    @AuraEnabled //Save Account Data
    Public static void createAccount(Account objacc){
        try{
            //Insert Account Record
            insert objacc; 
            
        }catch(Exception e){
            //throw exception message
            throw new AuraHandledException(e.getMessage());
        }
        finally {
        }
    }
    
    @AuraEnabled //get Account Industry Picklist Values
    public static Map<String, String> getIndustry(){
        Map<String, String> options = new Map<String, String>();
        //get Account Industry Field Describe
        Schema.DescribeFieldResult fieldResult = Account.Industry.getDescribe();
        //get Account Industry Picklist Values
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry p: pList) {
            //Put Picklist Value & Label in Map
            options.put(p.getValue(), p.getLabel());
        }
        return options;
    }
}

Component:
<!--Sample.cmp-->
<aura:component controller="SampleController" implements="flexipage:availableForAllPageTypes,force:appHostable">
    
    <!--Declare Attributes-->
    <aura:attribute name="industryMap" type="Map"/>
    <aura:attribute name="acc" type="Account" default="{'sobjectType':'Account', 
                                                       'Name': '',
                                                       'AccountNumber': '',
                                                       'Email': '',
                                                       'Phone': '', 
                                                       'Industry': ''}"/>
    
    <!--Declare Handler-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>  
    
    <!--Component Start-->
    <div class="slds-m-around--xx-large">
        <div class="container-fluid">
            <div class="form-group">
                <lightning:input name="accName" type="text" required="true" maxlength="50" label="Account Name" value="{!v.acc.Name}" />
            </div>
            <div class="form-group">
                <lightning:input name="accNumber" type="text" required="true" maxlength="10" label="Account Number" value="{!v.acc.AccountNumber}" />
            </div>
            <div class="form-group">
                <lightning:input name="accEmail" type="email" required="true" maxlength="100" label="Email" value="{!v.acc.Email}" />
            </div>
            <div class="form-group">
                <lightning:input name="accPhone" type="phone" required="true" maxlength="10" label="Phone" value="{!v.acc.Phone}" />
            </div>
            <div class="form-group">
                <!--Lightning radio group component-->
                <lightning:radioGroup name="radioGroup"
                                      label="Industry"
                                      required="true"
                                      options="{!v.industryMap}"
                                      value="{!v.acc.Industry}"
                                      type="radio"/>
            </div>
        </div>
        <br/>
        <lightning:button variant="brand" label="Submit" onclick="{!c.handleAccountSave}" />              
    </div>
    <!--Component End-->
</aura:component>

Controller:
({
    //Load Account Industry Picklist
    doInit: function(component, event, helper) {        
        helper.getIndustryPicklist(component, event);
    },
    
    //handle Account Save
    handleAccountSave : function(component, event, helper) {
        helper.saveAccount(component, event);
    },
    
    //handle Industry Picklist Selection
    handleCompanyOnChange : function(component, event, helper) {
        var indutry = component.get("v.acc.Industry");
        alert(indutry);
    }
})

Helper:
({
    //get Industry Picklist Value
    getIndustryPicklist: function(component, event) {
        var action = component.get("c.getIndustry");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                var industryMap = [];
                for(var key in result){
                    industryMap.push({label: result[key], value: key});
                }
                component.set("v.industryMap", industryMap);
            }
        });
        $A.enqueueAction(action);
    },
    
    //handle Account Save
    saveAccount : function(component, event) {
        var acc = component.get("v.acc");
        var action = component.get("c.createAccount");
        action.setParams({
            objacc : acc
        });
        action.setCallback(this,function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                alert('Record is Created Successfully');
            } else if(state === "ERROR"){
                var errors = action.getError();
                if (errors) {
                    if (errors[0] && errors[0].message) {
                        alert(errors[0].message);
                    }
                }
            }else if (status === "INCOMPLETE") {
                alert('No response from server or client is offline.');
            }
        });       
        $A.enqueueAction(action);
    }
})

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
This was selected as the best answer
Ravish Verma 15Ravish Verma 15
Thank you so much for the sample code and I am able to get the options in terms of radio button. I need little more help on this. I want to show saved value of the picklist field as the checked value in radio button. 
Narapa Naidu PulipatiNarapa Naidu Pulipati
Hi Khan Anis,

Wonderful Sample code. It really helped me acheive my requirement.Keep Going :)
Mrityunjaya VashishthaMrityunjaya Vashishtha
@Ravish Verma 15 ....did you get any POC for how to show saved option in radio Buttons for Picklist Value as per the above code.
Please share if you do.
Mrityunjaya VashishthaMrityunjaya Vashishtha
@Khan Anas,
Please help to find out ...how to show saved radio group option on UI for your provided code in Aura Components
 
Mrityunjaya VashishthaMrityunjaya Vashishtha
Hey Everyone
I have completed this functionality using Aura Components and the object level Picklist value is also Reflecting on the UI and its also editable..
Please refrence the below code:


<!-- file.cmp -->
<aura:component controller="RadioController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" 
access="global">

 <aura:attribute name="StatusMap" type="Map"/>
 <aura:attribute name="ReasonMap" type="Map"/>
 <aura:attribute name="PriorityMap" type="Map"/>
 <aura:attribute name="caseRecord" type="Object"/>
 <aura:attribute name="recordLoadError" type="String"/>
 <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <force:recordData aura:id="recordHandler"
    recordId="{!v.recordId}"
    fields="Status,Reason,Priority"
    targetFields="{!v.caseRecord}"
    targetError="{!v.recordLoadError}"
    mode="EDIT"
    recordUpdated="{!c.handleRecordUpdated}"
    />

 <lightning:recordEditForm aura:id="recordEditForm"
            recordId="{!v.recordId}"
            objectApiName="Case">

 <lightning:radioGroup name="radioGroup5"
                                      label="Reason"
                                      required="false"
                                      options="{!v.ReasonMap}"
                                      value="{!v.caseRecord.Reason}"
                                      variant="label-stacked"
                                      onchange="{!c.handleChange}"
                                      type="radio"
                                      style="display:inline-block !important"/>
<lightning:radioGroup name="radioGroup4"
                                      label="Status"
                                      required="false"
                                      options="{!v.StatusMap}"
                                      value="{!v.caseRecord.Status}"
                                      variant="label-stacked"
                                      onchange="{!c.handleChange}"
                                      type="radio"
                                      style="display:inline-block !important"/>
 <lightning:radioGroup name="radioGroup3"
                                      label="Priority"
                                      required="false"
                                      options="{!v.PriorityMap}"
                                      value="{!v.caseRecord.Priority}"
                                        variant="label-stacked"
                                      onchange="{!c.handleChange}"
                                      type="radio"
                                      style="display:inline-block !important"/>

 <div class="slds-docked-form-footer">
        <lightning:button aura:id="submit" onclick="{!c.editRecordNew}" label="Cancel" class="slds-m-top_medium_Cancel" />
  <lightning:button aura:id="submit" type="submit" label="Save" onclick="{!c.handleSaveRecord}" class="slds-m-top_medium" variant="brand" />
  </div>
</lightning:recordEditForm>
</aura:component>



<!-- file.controller.js -->
    
({
     doInit: function(component, event, helper) {      
        helper.getPriorityPicklist(component,event);
        helper.getStatusPicklist(component,event);
        helper.getReasonPicklist(component,event);
    },
     handleSaveRecord: function(component, event, helper) {
        component.find("recordHandler").saveRecord($A.getCallback(function(saveResult) {
            // NOTE: If you want a specific behavior(an action or UI behavior) when this action is successful 
            // then handle that in a callback (generic logic when record is changed should be handled in recordUpdated event handler)
            if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
                // handle component related logic in event handler
            } else if (saveResult.state === "INCOMPLETE") {
                console.log("User is offline, device doesn't support drafts.");
            } else if (saveResult.state === "ERROR") {
                console.log('Problem saving record, error: ' + JSON.stringify(saveResult.error));
            } else {
                console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error));
            }
        }));
    },
     handleRecordUpdated: function(component, event, helper) {
        var eventParams = event.getParams();
        if(eventParams.changeType === "CHANGED") {
            // get the fields that changed for this record
            var changedFields = eventParams.changedFields;
            console.log('Fields that are changed: ' + JSON.stringify(changedFields));
            // record is changed, so refresh the component (or other component logic)
            var resultsToast = $A.get("e.force:showToast");
            resultsToast.setParams({
                "title": "Saved",
                "message": "The record was updated."
            });
            resultsToast.fire();

        } else if(eventParams.changeType === "LOADED") {
            // record is loaded in the cache
        } else if(eventParams.changeType === "REMOVED") {
            // record is deleted and removed from the cache
        } else if(eventParams.changeType === "ERROR") {
            // there’s an error while loading, saving or deleting the record
        }
    }
        
})


<!-- file.helper.js -->


({
    getProductPicklist: function(component, event) {
        var action = component.get("c.getProduct");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                var ProductMap = [];
                for(var key in result){
                    ProductMap.push({label: result[key], value: key});
                }
                component.set("v.ProductMap", ProductMap);
            }
        });
        $A.enqueueAction(action);
    },
    getReasonPicklist: function(component, event) {
        var action = component.get("c.getReason");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                var ReasonMap = [];
                for(var key in result){
                    ReasonMap.push({label: result[key], value: key});
                }
                component.set("v.ReasonMap", ReasonMap);
            }
        });
        $A.enqueueAction(action);
    },
    getStatusPicklist: function(component, event) {
        var action = component.get("c.getStatus");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                var StatusMap = [];
                for(var key in result){
                    StatusMap.push({label: result[key], value: key});
                }
                component.set("v.StatusMap", StatusMap);
            }
        });
        $A.enqueueAction(action);
    }
   
})

<!-- file.controller.apxc -->

public class DSSRadioController {
    @AuraEnabled //Save Case Data
    Public static void createCse(Case objcse){
        try{
            //Insert Case Record
            insert objcse; 
            
        }catch(Exception e){
            //throw exception message
            throw new AuraHandledException(e.getMessage());
        }
        finally {
        }
    }
  
         @AuraEnabled //get Case Field Picklist Values
    public static Map<String, String> getStatus(){
        Map<String, String> options = new Map<String,String>();
        //get Case Field Describe
        Schema.DescribeFieldResult fieldResult = Case.Status.getDescribe();
        //get Case Filed Picklist Values
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry p: pList) {
            //Put Picklist Value & Label in Map
            options.put(p.getValue(), p.getLabel());
        }
        return options;
    }
    
    @AuraEnabled //get Case Field Picklist Values
    public static Map<String, String> getReason(){
        Map<String, String> options = new Map<String,String>();
        //get Case Field Describe
        Schema.DescribeFieldResult fieldResult = Case.Reason.getDescribe();
        //get Case Filed Picklist Values
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry p: pList) {
            //Put Picklist Value & Label in Map
            options.put(p.getValue(), p.getLabel());
        }
        return options;
    }
    
    @AuraEnabled //get Case Field Picklist Values
    public static Map<String, String> getProduct(){
        Map<String, String> options = new Map<String,String>();
        //get Case Field Describe
        Schema.DescribeFieldResult fieldResult = Case.Product_for_Ticket_Issuance__c.getDescribe();
        //get Case Filed Picklist Values
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry p: pList) {
            //Put Picklist Value & Label in Map
            options.put(p.getValue(), p.getLabel());
        }
        return options;
    }
}


""""""""Please Mark it as the Best Answer for others reference..""""""""""


Regards to all
Mrityunjaya Vashishtha