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
K RoyK Roy 

Lightning Combobox Issue

Hello Team,

I have recently started working in lightning. I am trying to work on a scenario, where i will be displaying the Account name in a dropdown. On selecting an Account, it will show the corresponding Contacts associated with the account. To achieve this, i am using lightning:Combobox.

My Component:
 
<aura:component implements="flexipage:availableForAllPageTypes" access="global" controller ="AccountDropDownListController">
    <aura:attribute name="accounts" type ="Account[]"/>
    <aura:handler name = "init" value="{!this}" action="{!c.init}" />
    <lightning:combobox name="general" label="Account List" placeholder="Select an Account" options="{! v.accounts }" onchange="{! c.handleChange }"/>
</aura:component>

Apex Controller:

public class AccountDropDownListController {
    @AuraEnabled
      public static List <String> getAccounts() 
      {
          List<Account> lstAccount= [SELECT Id, name, industry, Type, NumberOfEmployees, TickerSymbol, Phone FROM Account ORDER BY createdDate ASC];
          List<String> lstStrngAccount = new List<String>();
          for(Account acc:lstAccount)
          {
            lstStrngAccount.add(acc.Name);  
          }
          return lstStrngAccount;
      }
    }

Client Side Controller:

({
    init: function (component, event, helper) {
        helper.getAccountList(component);
    },
    handleChange: function (component, event,helper) {
        // This will contain the string of the "value" attribute of the selected option
        var selectedAccountValue = event.getParam("value");
        alert("Account selected with value: '" + selectedAccountValue + "'");
    }
})

Helper:

({
      getAccountList: function(component) {
    var action = component.get('c.getAccounts');
    var self = this;
    action.setCallback(this, function(actionResult) {
    component.set('v.accounts', actionResult.getReturnValue());
    var k = actionResult.getReturnValue();
    var items = [];
        for (var i = 0; i < k.length; i++) {
            var item = {
                "label": k[i] + " Option",
                "value": k[i].toString(),
            };
            items.push(item);
        }
        component.set("v.accounts", items);
   });
    $A.enqueueAction(action);
  }
})

What i am unable to do is, i am not able to click the Accounts, that i am selecting. How can i do that? Also after clicking, how can i get the corresponding contacts associated with those accounts?

Request you all to kindly guide me on this.

Regards,
Rahul
Khan AnasKhan Anas (Salesforce Developers) 
Hi Rahul,

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 AccountInComboboxC {
    
    @AuraEnabled
    public static List<String> getAcc() {
        List<Account> lstAccs = [SELECT Id, Name FROM Account];
        List<String> acList = new List<String>();
        for(Account a : lstAccs){
            acList.add(a.Name) ;
        }
        return acList;
    }
    
    @AuraEnabled
    public static List<Contact> fetchCon (String recordId){
        return [SELECT Id, Name, Phone FROM Contact WHERE Account.Name=:recordId];
    }
}

Component:
<aura:component controller="AccountInComboboxC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="accList" type="String[]" default="[]"/> 
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}"/>
    
    <lightning:combobox name="general" label="Account List" 
                        placeholder="Select an Account" 
                        options="{!v.accList}" 
                        value="New"
                        onchange="{!c.showCon}"/>
    
    <lightning:datatable data="{! v.mydata }" 
                         columns="{! v.mycolumns }" 
                         keyField="Id" />
</aura:component>

Controller:
({
    doinit : function (component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Name', fieldName: 'Name', type: 'text'},
            {label: 'Phone', fieldName: 'Phone', type: 'phone'}
        ]);    
        
        var action = component.get("c.getAcc");
        action.setCallback(this, function(response){
            var state = response.getState();
            if (state === "SUCCESS") {
                var listItems = response.getReturnValue();
                console.log('Account List -> ' + listItems);
                var options = [];
                listItems.forEach(function(element) {
                    options.push({ value: element, label: element });
                });
                component.set("v.accList", options);
            }
        });
        
        $A.enqueueAction(action);
    },
    
    showCon : function (component, event, helper) {
        var selectedAccountValue = event.getParam("value");
        console.log('selectedAccountValue.Id -> ' + selectedAccountValue);
        var action = component.get('c.fetchCon');
        action.setParams({recordId : selectedAccountValue});
        action.setCallback(this, function(response){
            var state = response.getState();
            if(state === "SUCCESS"){
                var allValues = response.getReturnValue();
                console.log("allValues--->>> " + JSON.stringify(allValues));
                component.set('v.mydata', allValues);
            }
            else if(state === "ERROR") {
                var errors = response.getError();
                if(errors){
                    if(errors[0] && errors[0].message){
                        console.log("Error Message: " + errors[0].message);
                    }
                }
                else{
                    console.log("Unknown Error");
                }
            }
        });
        $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
K RoyK Roy
Hi Anas,

It worked for me too. Thanks for the solution. However, can you tell me, how can i remove the checkbox from the contacts table? I dont need it as of now.
Khan AnasKhan Anas (Salesforce Developers) 
Hi Rahul,

It's my pleasure. I’m glad I was able to help!

You can use hideCheckboxColumn="true" attribute in lightning:datatable to disable the checkboxes. 
 
<lightning:datatable data="{! v.mydata }" 
                         columns="{! v.mycolumns }" 
                         keyField="Id" 
                         hideCheckboxColumn="true" />

Kindly mark this as solved if it's resolved so that it gets removed from the unanswered queue which results in helping others who are encountering a similar issue.

Regards,
Khan Anas
K RoyK Roy
Hello Anas,

Its working fine as expected. Thanks for the help. One more thing, if i want to delete the contacts one by one, based on the accounts, how to do that?

Can you kindly help on this?

Regards,
Rahul