+ Start a Discussion
Soundar Raj PonpandiSoundar Raj Ponpandi 

How Can I Display Picklist values From Record ?

HI,

I would like to display a picklist value from record.

1. I am using one custom object it's called "GD_Offer__c ". I want to display a field as  a picklist with reference of "GD_Offer__c" records.

2. For example i have 3 following records in this "GD_Offer__c" table, I need to display those records in picklist value.

       A. Offer A
       B. Offer B
       C. Offer C


I wrote coding for this functionality, I am not sure where i did a mistake. Can you please guide me where i did a mistake and what are all the changes i need to do to achieve mentioned functionality.


Apex Class Method 
@AuraEnabled 
     public static Map<String, String> getOffers(){
        system.debug('Entered into the Get Offers ********'); 
        Map<String, String> options = new Map<String, String>();
        Schema.DescribeFieldResult fieldResult = GD_Offers__c.Name.getDescribe();
         system.debug('fieldResult | ' + fieldResult);
        List<Schema.PicklistEntry> pList = fieldResult.getPicklistValues();
         system.debug('pList ' + pList);
        for (Schema.PicklistEntry p : pList) {
            options.put(p.getValue(), p.getLabel());
        }
        system.debug('Options |' + options);
        return options;
    }

Component
 
<aura:attribute name="offerMap" type="Map"/>

<table>
<tr>
<td>
                            <lightning:recordEditForm aura:id="form" objectApiName="GD_Quote_Line_Items__c" >
                               
                                <div class="form-group">
                                    <lightning:select aura:id="industryPicklist" value="{!v.lineItem.GD_Offers__c}" onchange="{!c.handleCompanyOnChange}">
                                        <option value="">--None--</option>
                                        <aura:iteration items="{!v.offerMap}" var="ind" indexVar="key">
                                            <option text="{!ind.value}" value="{!ind.key}" selected="{!ind.key==v.lineItem.GD_Offers__c}" />
                                        </aura:iteration>
                                    </lightning:select>
                                </div>
                            </lightning:recordEditForm>
                        </td>
</tr>
</table>

Controller.JS
doInit: function(component, event, helper) {
        helper.getOfferPicklist(component, event);
    },

Helper.JS
getOfferPicklist: function(component, event) {
        alert('Entered Offer Picklist');
        var action = component.get("c.getOffers");
        action.setCallback(this, function(response) {
            var state = response.getState();
            alert('State = ' + state);
            if (state === "SUCCESS") {
                var result = response.getReturnValue();
                var offerMap = [];
                for(var key in result){
                    offerMap.push({key: key, value: result[key]});
                }
                component.set("v.offerMap", offerMap);
            }
        });
        $A.enqueueAction(action);
    },


Thanks In Advance,
Soundar.
Thanskn
Best Answer chosen by Soundar Raj Ponpandi
Soundar Raj PonpandiSoundar Raj Ponpandi
HI David,

I did few changes in my coding. Now it's working as expected.

Core Changes
<td>
     <lightning:select value="{!lineItem.GD_Offers__c}">
     <aura:iteration items="{!v.offers}" var="offer" >
     <option  value="{!offer.value}" >{!offer.label}</option> 
     </aura:iteration>
     </lightning:select>
</td>


Controller.JS
getOfferPicklist: function(component, event) {
        var action = component.get("c.queryOffers");
            action.setCallback(this, function(data) {
                var result = data.getReturnValue()
				var opts = [];
			for (var i in result){
                console.log(i);
                    opts.push({
                        class: "optionClass",
                        label: result[i],
                        value: i
                    });
                }
                component.set("v.offers", opts);
        });
        $A.enqueueAction(action);
        
    },

Apex class
@AuraEnabled
    public static Map<String, String> queryOffers() {
        Map<String, String> offers = new Map<String, String>();
        for(GD_Offers__c off : [select ID, Name from GD_Offers__c]) {
        	offers.put(off.id, off.Name);     
        }
        return offers; 
    }

I am choosing my answer as best answer for othres reference.

Regards,
Soundar.
 

All Answers

David Zhu 🔥David Zhu 🔥
I would sugget making the following changes.
1. Apex method getOffers.
   You used schema.DescribeFieldResult. The class is to get the picklist values from a field.
    In your case, you have three records in GD_Offer__c object.
     Simply use soql to get the records and build the map.
     list<gd_offer__c> gdoffers = [select name from gd_offer__c];

2. In Aura component html.
   You use <lightning:recordEditForm> to create the record. <lightning:recordEditForm> is commonly used to use Salesforce data service without create your own submit handler (apex method).
    <lightning:recordEditForm> can talk to field directly. It is usually having <lighting:inputfield> wrapped. 
    i.e.
   <lightning:recordEditForm recordId="003XXXXXXXXXXXXXXX" objectApiName="Contact">
        <lightning:messages />
        <lightning:outputField fieldName="AccountId" />
        <lightning:inputField fieldName="FirstName" />
        <lightning:inputField fieldName="LastName" />
        <lightning:inputField fieldName="Email" />
</lightning:recordEditForm>

  So, you might not use Lighntining data service. Instead, put the filed on the lighting component and create your own apex method to save the data.
 You can use lightning:combobox component to display the picklist,consequently, modify this line: <aura:attribute name="offerMap" type="Map"/>
to <aura:attribute name="offerMap" type="List"/> and modifiy js helper controller when populating the data.
 See sample here
https://developer.salesforce.com/docs/component-library/bundle/lightning:combobox/example
 
Soundar Raj PonpandiSoundar Raj Ponpandi
Hi David,

Thanks for your quik response.

I have changed my coding as well, Now this offer value could not pass into the save method. Can you please check and let me know where i did mistake.

Component
<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickActionWithoutHeader" access="global" controller="GD_QuotePackages">
    
	
	<aura:attribute name="quote" type="GD_Quote__c"  default="{'sobjectType':'GD_Quote__c', 'name':''}"/>     
    <aura:attribute name="lineItem" type="GD_Quote_Line_Items__c"  default="{'sobjectType':'GD_Quote_Line_Items__c',
                                                                  'GD_Offers__c':'',
                                                                  'GD_Packages__c' : '',
                                                                  'GD_Primary__c' : ''
                                                                  }"/> 
    <aura:attribute name="recordId" type="String" />
    
    <aura:attribute name="lineItemList" type="GD_Quote__c[]"/>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute name="offerMap" type="Map"/>
    <aura:attribute name="offers" type="list"/>
    <aura:attribute name="selectedOffer" type="String[]"/> 
    <ltng:require styles="{!$Resource.GD_ModalWidth}"/>
    
    <div class="slds">
        <h1 align="center" style="font-size: 18px;">Create Offers / Packages</h1><hr/>
        <table class="slds-table slds-table_cell-buffer slds-table_bordered">
            <thead>
                <tr class="slds-line-height_reset">
                    <th class="" scope="col">
                        <div class="slds-truncate" title="Opportunity Name">Sr.No</div>
                    </th>
                    <th class="" scope="col">
                        <div class="slds-truncate" title="Account Name">Product Code</div>
                    </th>
                    <th class="" scope="col">
                        <div class="slds-truncate" title="Stage">Offer</div>
                    </th>
                    <th class="" scope="col">
                        <div class="slds-truncate" title="Confidence">Packages</div>
                    </th>
                    <th class="" scope="col">
                        <div class="slds-truncate" title="Contact">Primary</div>
                    </th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.lineItemList}" var="lineItem" indexVar="index">  
                    <tr class="slds-hint-parent">
                        <th>
                            <div class="slds-truncate" title="index">
                                {!index + 1}
                            </div>
                        </th>
                        <td>
                            <div class="slds-truncate" title="Product Code">{!lineItem.GD_Item_Code__c}</div>
                        </td>
                        <td>
                            <lightning:recordEditForm aura:id="form" objectApiName="GD_Quote_Line_Items__c" >
                            <lightning:select>
                                <aura:iteration items="{!v.offers}" var="offer">
                                    <option text="{!offer.label}" value="{!lineItem.GD_Offers__c}" selected="{!offer.selected}"></option>
                                </aura:iteration>
                            </lightning:select>
                            </lightning:recordEditForm>
                        </td>
                        <td>
                            <lightning:recordEditForm aura:id="form" objectApiName="GD_Quote_Line_Items__c" >
                                <br/><lightning:inputField variant="label-hidden" aura:id="packages" value="{!lineItem.GD_Packages__c}" fieldName="GD_Packages__c"></lightning:inputField>
                            </lightning:recordEditForm>
                        </td>
                        
                        <td>
                           <lightning:recordEditForm aura:id="form" objectApiName="GD_Quote_Line_Items__c" >
                                <br/><!--<lightning:inputField type="checkbox" variant="label-hidden" aura:id="primary" value="{!lineItem.GD_Primary__c}" fieldName="GD_Primary__c"></lightning:inputField>-->
                               <ui:inputCheckbox aura:id="primary" value="{!lineItem.GD_Primary__c}" ></ui:inputCheckbox> 
                            </lightning:recordEditForm>
                        </td>
                    </tr>
                    
                </aura:iteration>
            </tbody>
        </table>
        <div class="slds-docked-form-footer">
            <div class="slds-col_bump-left slds-text-align_right">
                <br/><br/>
                <ui:button label="Save" press="{!c.save}" class="customButton" />
                <ui:button label="Cancel" press="{!c.doCancel}" class="customButton"/>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br/><br/>
            </div>
        </div> 
    </div> 
</aura:component>

Controller.JS
 
({
    doInit: function(component, event, helper) {
        helper.getPackagesRecHelper(component, event, helper);
        helper.getOfferPicklist1(component, event);
    },
    
    save: function(component, event, helper) {
            helper.saveQuoteLineItemList(component, event);
    },
    
	doCancel: function(component, event) {
        var close = $A.get("e.force:closeQuickAction").fire();
        close.fire();
    },
})

Helper.JS
({
    getPackagesRecHelper: function (component, event, helper) {
        var action = component.get("c.GD_showQuoteLineItems");
        action.setParams({
            quoteId: component.get("v.recordId")
        });
        action.setCallback(this, function(data){
            component.set("v.lineItemList",data.getReturnValue());
        }); 
        $A.enqueueAction(action);
    },
    
    
    getOfferPicklist1: function(component, event) {
        var action = component.get("c.queryOffers");
            action.setCallback(this, function(data) {
                var result = data.getReturnValue()
				var opts = [];
			for (var i in result){
                    opts.push({
                        class: "optionClass",
                        label: result[i],
                        value: i
                    });
                }
                component.set("v.offers", opts);
        });
        $A.enqueueAction(action);
        
    },    
     saveQuoteLineItemList: function(component, event, helper) {
        var action = component.get("c.GD_UpdateQtLnItem");
        var toastEvent = $A.get("e.force:showToast");
        action.setParams({
            "lineItemList": component.get("v.lineItemList"),
            quteId: component.get("v.recordId"),
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.lineItemList", []);
                /*Toast Message*/
                toastEvent.setParams({
                    title: "Success!",
                    message: "Packages / Offers has been updated successfully!",
                    type: "success"
                });
                toastEvent.fire();
                
                /*Navigation*/
                var recId = component.get("v.recordId");
                var sObectEvent = $A.get("e.force:navigateToSObject");
                sObectEvent .setParams({
                    "recordId": recId,
                    "slideDevName": "detail"
                });
                sObectEvent.fire();
            }
        }); 
        $A.enqueueAction(action);
    },
})

Apex Controller
public class GD_QuotePackages {
    
    @AuraEnabled
    public static List<GD_Quote_Line_Items__c> GD_showQuoteLineItems(Id quoteId){
        system.debug('Entered *********');
        List<GD_Quote_Line_Items__c> lineItemList = [select Id,GD_Quote__c,GD_Item_Code__c,GD_Offers__c, GD_Packages__c, GD_Primary__c from GD_Quote_Line_Items__c WHERE GD_Quote__c =: quoteId];  
        system.debug('Return List ***** |' + lineItemList);
        return lineItemList;
    }
    
    @auraenabled
    public static id GD_UpdateQtLnItem(List<GD_Quote_Line_Items__c> lineItemList,String quteId){
        try{
            system.debug('Team List Size |' + lineItemList.size());
            system.debug('Quote Id |' + quteId);
            system.debug('lineItemList |' + lineItemList);
            for(GD_Quote_Line_Items__c irow :lineItemList){
                system.debug('Primary is ' + irow.GD_Primary__c + ' for ' + irow.GD_Offers__c);
            }
            if(lineItemList.size() >0){
                update lineItemList;
            }      
        }catch(Exception e){
            system.debug('Exception | ' + e);
        }
        return null; 
    }

    @AuraEnabled
    public static Map<String, String> queryOffers() {
        Map<String, String> offers = new Map<String, String>();
        for(GD_Offers__c off : [select ID, Name from GD_Offers__c]) {
        	offers.put(off.id, off.Name);     
        }
        return offers; 
    }

    
}

Thanks in Advance,
Soundar. ​​​​​​​
Soundar Raj PonpandiSoundar Raj Ponpandi
Hi David,

That code is not working properly.

Exactly i am looking for,

1. Display Offer Lookup as a picklist (I did by using List method).

2. Now Selected picklist Value shoud update in the lookup field (I am struggling on that)

Regards,
Soundar.
Soundar Raj PonpandiSoundar Raj Ponpandi
HI David,

I did few changes in my coding. Now it's working as expected.

Core Changes
<td>
     <lightning:select value="{!lineItem.GD_Offers__c}">
     <aura:iteration items="{!v.offers}" var="offer" >
     <option  value="{!offer.value}" >{!offer.label}</option> 
     </aura:iteration>
     </lightning:select>
</td>


Controller.JS
getOfferPicklist: function(component, event) {
        var action = component.get("c.queryOffers");
            action.setCallback(this, function(data) {
                var result = data.getReturnValue()
				var opts = [];
			for (var i in result){
                console.log(i);
                    opts.push({
                        class: "optionClass",
                        label: result[i],
                        value: i
                    });
                }
                component.set("v.offers", opts);
        });
        $A.enqueueAction(action);
        
    },

Apex class
@AuraEnabled
    public static Map<String, String> queryOffers() {
        Map<String, String> offers = new Map<String, String>();
        for(GD_Offers__c off : [select ID, Name from GD_Offers__c]) {
        	offers.put(off.id, off.Name);     
        }
        return offers; 
    }

I am choosing my answer as best answer for othres reference.

Regards,
Soundar.
 
This was selected as the best answer
David Zhu 🔥David Zhu 🔥
Glad to hear you have your problem resolved