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
Pankaj Sharma 195Pankaj Sharma 195 

How to show PickList field as Radio Buttons on Lightning Component ?

Pankaj Sharma 195Pankaj Sharma 195
i want to create radio buttons group having yes and no values by using a custom field of an custom object. that field is a picklist type having yes and no two options. and also on click of radio button value it should saved in that custom field .
 
sfdcMonkey.comsfdcMonkey.com
hi pankaj here is the sample code for it :
am using the account object and in account object i have a custom picklist type field VIP_Account__c with 2 value "Yes" and "No"
 
<aura:component  controller="testLC">
	  <aura:attribute name="options" type="List" default="[
             {'label': 'Yes', 'value': 'Yes'},
             {'label': 'No', 'value': 'No'}
       ]"/>
    
    <aura:attribute name="picklistValue" type="String"/>
    <aura:attribute name="accObj" type="account" default="{ 'sobjectType' : 'Account',
                                                             'Name' : '',
                                                             'VIP_Account__c' : ''
                                                           }"/>
    
    <ui:inputText label="Name" value="{!v.accObj.Name}"/>
    
    <br/>
    
    <lightning:radioGroup 
        aura:id="mygroup"
        name="radioButtonGroup"
        label="Is VIP Account"
        options="{! v.options }"
        value="{! v.picklistValue}"
    />
    
    <button class="slds-button slds-button_brand" onclick="{!c.saveAcc}">Save</button>
</aura:component>

js controller
({
	saveAcc: function (component, event) {
        var tempAccount = component.get("v.accObj");
        var vipVal = component.get("v.picklistValue");
        
        if(vipVal != undefined && vipVal.length > 0){
            tempAccount.VIP_Account__c = vipVal[0]; 
        }   
          
        var action = component.get("c.saveAccount");
        action.setParams({
            acc: tempAccount,
        });
 
        action.setCallback(this, function(response) {
            alert(response.getState());          
        });
        $A.enqueueAction(action);
    },
    
    
})

apex controller
public class testLC {
   @AuraEnabled 
    public static void saveAccount(Account acc){
        insert acc;
    }
}

​​output :
User-added image

i hope it helps you.
   Let me inform if it helps you and kindly mark it best answer if it helps you so it make proper solution for others

thanks 
http://sfdcmonkey.com  (http://sfdcmonkey.com )


 
Sara Morgan 21Sara Morgan 21
Hi Piyush,
Thank you so much for the above example, I have tried the same with lightning:checkboxGroup

<lightning:checkboxGroup name="Checkbox Group"
                                                             options="{! v.options }"
                                                             value="{! v.value }"
                                                             />
now if I select more than one checkboxes and hit the submit button i get an error and when I select one checkbox I get no error but the selected checkbox just doesn't save in my salesforce org.

could you please suggest on this?
Thank you in anticipation
Sara Morgan 21Sara Morgan 21
Please ignore, I solved the error but still thank you so much for the above example
Thulasi ReddyThulasi Reddy

HI sara morgan

could you please share How to show PickList field as Checkbox on Lightning Component

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