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
Prashant Sharma 157Prashant Sharma 157 

I want to show contact related to particular account.Ex. I am having a dropdown having account list, i want to get whole contacts of that account while click on that account

Khan AnasKhan Anas (Salesforce Developers) 
Hi Prashant,

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.

Visualforce:
<apex:page controller="AccPicklistConRelatedC">
    <apex:form >
        <apex:pageBlock title="Account Name">
            Account Names&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
            
            <apex:selectList value="{!selectedAccId}" size="1">                                 
                <apex:selectOptions value="{!AccountNames}"/>
                <apex:actionSupport event="onchange" action="{!ShowTable}" />
            </apex:selectList>
            
            <br/><br/>
            
            Related Contact Names: <br/><br/>
            
            <apex:pageBlockTable value="{!ContactNames}" var="items">
                <apex:column value="{!items.Name}"/>
                <apex:column value="{!items.Phone}"/>
            </apex:pageBlockTable>            
        </apex:pageBlock>           
    </apex:form>
</apex:page>

Controller:
public class AccPicklistConRelatedC {

    public String selectedAccId{get;set;}
    public List<Contact> ContactNames{get;set;}
    
    public List<SelectOption> getAccountNames() {
        List<SelectOption> accOptions= new List<SelectOption>();
        accOptions.add( new SelectOption('','--Select--'));
        for( Account acc : [SELECT Id, Name FROM Account ] ) {
            accOptions.add( new SelectOption(acc.Id,acc.name));
        }
        return accOptions;
    }
    
    public void ShowTable() {
        ContactNames = new List<Contact>(); 
        for(Contact cr : [SELECT Id, Name, Phone FROM Contact WHERE AccountId=:selectedAccId]){
            ContactNames.add(cr);
        }
    }
}

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
Prashant Sharma 157Prashant Sharma 157
Can you provide the whole slution in salesforce lightning?
Khan AnasKhan Anas (Salesforce Developers) 
Hi Prashant,

I have created a lightning component according to your requirements. Please try the below code:

Apex:
public class AccPicklistRelatedConC {
    
    @AuraEnabled
    public static List<Account> getAccountName() {
        List<Account> lstNames = [SELECT Id, Name FROM Account];
        return lstNames;
    }
    
    @AuraEnabled
    public static List<Contact> getConatct(String aName) {
        List<Contact> con = [SELECT Id, Name, Phone, Email, Account.Name FROM Contact WHERE Account.Name=:aName];
        return con;
    }
}

Component:
<aura:component controller="AccPicklistRelatedConC"
                implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,forceCommunity:availableForAllPageTypes,force:lightningQuickAction" access="global" >
    
    <aura:attribute name="PageHeading" type="String" default="Show Contact Records Related to Account"/>
    <aura:attribute name="pickName" type="List" />
    <aura:attribute name="picksel" type="String" />
    <aura:attribute name="mydata" type="Contact"/>
    <aura:attribute name="mycolumns" type="List"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doinit}"/>
    
    <div class="slds-m-top--xx-large">
        <div class="slds-page-header">
            <div class="slds-align--absolute-center">
                <div class="slds-text-heading--large">       
                    {!v.PageHeading}
                </div>
            </div>
        </div>
    </div>
    <br/> <br/>
    
    <div class = "slds-size--3-of-8">
        <lightning:select aura:id="selectid" label="Select Account Name" value="{!v.picksel}" onchange="{!c.onControllerFieldChange}" >
            <option value="" text="- None -" />
            <aura:iteration items="{!v.pickName}" var="pick">
                <option value="{!pick.Name}" text="{!pick.Name}" />
            </aura:iteration>
        </lightning:select>
        <br/><br/>
    </div>
    <br/><br/>
    
    <div class="slds-p-left_large slds-p-right_medium">
        
        <lightning:datatable data="{! v.mydata }" 
                             columns="{! v.mycolumns }" 
                             keyField="Id" 
                             hideCheckboxColumn="true"/>
    </div>
</aura:component>

Controller:
({
    doinit : function(component, event, helper) {
        component.set('v.mycolumns', [
            {label: 'Contact Name', fieldName: 'Name', type: 'text'},
            {label: 'Phone', fieldName: 'Phone', type: 'phone'},
            {label: 'Email', fieldName: 'Email', type: 'email'},
            {label: 'Account Name', fieldName: 'AccountName', type: 'text'}
        ]);
        
        var action = component.get("c.getAccountName");
        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.pickName", 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);
    },
    
    onControllerFieldChange : function(component, event, helper){
        var pickselected = component.find("selectid").get("v.value");
        console.log('pickselected--->>> ' + pickselected);
        var action = component.get("c.getConatct");
        action.setParams({aName : pickselected});
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                var allValues = response.getReturnValue();
                console.log('allValues--->>> ' + JSON.stringify(allValues));
                for (var i = 0; i < allValues.length; i++) {
                    var row = allValues[i];
                    if (row.Account) row.AccountName = row.Account.Name;
                }
                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);
    }
})

CSS:
.THIS {
}

.THIS.slds-size--3-of-8 {
    margin-left: 420px;
}

Application:
<aura:application extends="force:slds">
    <c:AccPicklistRelatedCon/>	
</aura:application>

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.

Regards,
Khan Anas