+ Start a Discussion
basha skbasha sk 

How to get selected value from selectOption values dropdown list


Here in visualforce page i have two selectoption dropdownlists.
Account list
Contacts list
In accounts list i'm displaing all salesforce accounts and based on the selected account I'm displaying the related contacts in Contacts list.
After getting the selected contact i'm mapping that contact details to the other custom object.
Req: How to filter the selected contact record from selectedOption list?
This is my apex class:
public with sharing class Picklist{
public String selectedAccId{get;set;}
public String selectedConId{get;set;}
public String selectedContactId{get;set;}
public String firstname;
public String lastname;
public String email;
public String company;
public String mailingcity;
public String mailingstate;
public String mailingcountry;
public String mobileno;
public Status__c login1;
List<System.SelectOption> conOptions{get;set;}
List<System.SelectOption> options{get;set;}
public Picklist(ApexPages.StandardController controller){
this.login1= (Status__c)controller.getRecord();
}
public List<System.SelectOption> accOptions{get;set;}
//getting all salesforce accounts
public List<System.SelectOption> getAccountNames(){
List<System.SelectOption> accOptions= new List<System.SelectOption>();
accOptions.add( new System.SelectOption('','--Select--'));
for( Account acc : [select Id,name from Account] ){
accOptions.add( new System.SelectOption(String.valueOf(acc.Id),acc.name));
} return accOptions;
} //displaying all related contacts based the selectd account record. public List<System.SelectOption> getContactNames(){
List<System.SelectOption> conOptions= new List<System.SelectOption>();
if(selectedAccId != null){
for(contact con : [select Id,name,accountid,FirstName,LastName,email,MobilePhone,MailingCity,MailingState,MailingCountry from contact where accountid=:selectedAccId ]){
conOptions.add(new System.SelectOption(String.valueOf(con.Id),con.name));
System.debug('conOptions:::'+conOptions);
}
}
return conOptions;
}
//how to get the contact record from conatcs list.
public Pagereference getSelectedContact(){
System.debug('Entered Selected contact id...........'+selectedConId );
List<System.SelectOption> options = new List<System.SelectOption>();
if(conOptions.size() > 0){
System.debug('SelectId::::'+selectedConId);
for(Contact con1 : [select Id, name, Account.Name, accountid, FirstName, LastName, email, MobilePhone, MailingCity, MailingState, MailingCountry from contact where id=:selectedConId]){
firstname = con1.FirstName;
System.debug('Entered ContactNames contact id...........'+firstname);
lastname= con1.LastName; System.debug('lastname:::'+lastname);
email = con1.Email;
System.debug('email:::'+email );

}
}
else{ conOptions.add( new System.SelectOption('--None--','--None--')); } return null; } }

Thanks in advancce if anybody having idea please let me know
Best Answer chosen by basha sk
jigarshahjigarshah
Basha,

I believe once a Contact is selected in the picklist you will have the Record Id of the selected Contact captured in the selectedContactId property from my code snippet above.

Use the below code to identify the Contact record and map its values to another object's fields. Refer the code below with the additional methods to filter the selected Contact record based on the selection within the Contact picklist. Addition to this code are the getSelectedContact() and populateContactDetails() methods.
public with sharing class Picklist{

	public Map<Id, Account> accountIdRecordMap {get; set;}
	public Status__c login1 {get; set;};
	
	public List<System.SelectOption> accOptions{get;set;}
	public Id selectedAccId {get; set;}
	public List<System.SelectOption> conOptions{get;set;}
	public Id selectedContactId {get; set;}
	
	public Contact selectedContact {get; set;}
	public YourCustomObject__c customObjInstance {get; set;}
	
	//Constructor
	public Picklist(ApexPages.StandardController controller){
		this.login1 = (Status__c)controller.getRecord();
		init();
	} 

	//Retrieve most recent 500 Accounts and associated Contacts
	public Map<Id, Account> getAccountsWithContacts(){
	
		if(this.accountIdRecordMap == null){
			
			this.accountIdRecordMap = [Select Id, Name,
										(
											Select Id,
												   name,
												   accountid,
												   FirstName,
												   LastName,
												   email,
												   MobilePhone,
												   MailingCity,
												   MailingState,
												   MailingCountry 
											From Account.Contacts 
										)
									  From Account
									  Order by CreatedDate DESC
									  Limit 500];
		}
		
		return this.accountIdRecordMap;
	}
	
	//Populate account picklist options
	public void getAccountNames(){
		
		if(this.accOptions.size() == 0){
		
			this.accOptions.add(new System.SelectOption('' , '--Select--'));
		
			for(Id accRecId :accountIdRecordMap.keySet()){
				this.accOptions.add(
					new System.SelectOption(
						accRecId, 
						accountIdRecordMap.get(accRecId).Name
					)
				);
			}//for
		} 
	}
	
	//Populate related Contact picklist options
	public void getContactsByAccountId(Id pAccountId){

		this.conOptions.add(new System.SelectOption('' , '--Select--'));
		if(accountIdRecordMap.keySet().containsKey(pAccountId)){

			for(Contact contactRec :((Account)accountIdRecordMap.get(pAccountId)).Contacts){
			
				this.conOptions.add(
					new System.SelectOption(
						contactRec.Id, 
						contactRec.Name
					)
				);
			}//for
		}
	}
	
	//Retrieves the selectedContact Record information based on the selected Account Id
	public void getSelectedContact(){
	
		if(accountIdRecordMap.keySet().containsKey(pAccountId)){

			for(Contact contactRec :((Account)accountIdRecordMap.get(pAccountId)).Contacts){
				if(contactRec.Id == selectedContactId){
					this.selectedContact = contactRec;
				}
			}
		}//if
	}
	
	//Assumes selectedContact is populated with the Contact record information
	public void populateContactDetails(){
	
		if(this.selectedContact <> null){
	
			this.customObjInstance = new YourCustomObject__c(
				CustomField1__c = this.selectedContact.FirstName,
				CustomField2__c = this.selectedContact.LastName,
				CustomField3__c = this.selectedContact.Email,
				CustomField4__c = this.selectedContact.MobilePhone,
				CustomField5__c = this.selectedContact.MailingCity
				.
				.
				//Add all Contact field mappings here
			);
		}
	}
	
	//Private Methods
	private void init(){
		accOptions = new new List<System.SelectOption>();
		conOptions = new new List<System.SelectOption>();
	}
}

All Answers

v varaprasadv varaprasad
Hi Basha,

you need to use :apex:selectList value=​
 
====Vf Page

<apex:selectList value="{!selectedvalue}" multiselect="false" size="1" >
      <apex:selectOptions value="{!items}" />
      </apex:selectList>

====In controller : 

public string selectedvalue{get;set;}

Hope this helps you!

Thanks
Varaprasad
For Support: varaprasad4sfdc@gmail.com
jigarshahjigarshah
Use the below mentioned Apex Controller Code to filter out Contact records for the chosen Account record. The technique is to query Accounts and Contacts at once and then filter out in memory and display the related Contacts in the dependent dropdown.

Keep a tab on the number of results returned and hence the below code only retrieves 500 most recent Accounts and their associated Contacts.
 
public with sharing class Picklist{

	public Map<Id, Account> accountIdRecordMap {get; set;}
	public Status__c login1 {get; set;};
	
	public List<System.SelectOption> accOptions{get;set;}
	public Id selectedAccId {get; set;}
	public List<System.SelectOption> conOptions{get;set;}
	public Id selectedContactId {get; set;}
	
	//Constructor
	public Picklist(ApexPages.StandardController controller){
		this.login1 = (Status__c)controller.getRecord();
		init();
	} 

	//Retrieve most recent 500 Accounts and associated Contacts
	public Map<Id, Account> getAccountsWithContacts(){
	
		if(this.accountIdRecordMap == null){
			
			this.accountIdRecordMap = [Select Id, Name,
										(
											Select Id,
												   name,
												   accountid,
												   FirstName,
												   LastName,
												   email,
												   MobilePhone,
												   MailingCity,
												   MailingState,
												   MailingCountry 
											From Account.Contacts 
										)
									  From Account
									  Order by CreatedDate DESC
									  Limit 500];
		}
		
		return this.accountIdRecordMap;
	}
	
	//Populate Account picklist options
	public void getAccountNames(){
		
		if(this.accOptions.size() == 0){
		
			this.accOptions.add(new System.SelectOption('' , '--Select--'));
		
			for(Id accRecId :accountIdRecordMap.keySet()){
				this.accOptions.add(
					new System.SelectOption(
						accRecId, 
						accountIdRecordMap.get(accRecId).Name
					)
				);
			}//for
		} 
	}
	
	//Populate related Contact picklist options
	public void getContactsByAccountId(Id pAccountId){

		this.conOptions.add(new System.SelectOption('' , '--Select--'));
		if(accountIdRecordMap.keySet().containsKey(pAccountId)){

			for(Contact contactRec :((Account)accountIdRecordMap.get(pAccountId)).Contacts){
			
				this.conOptions.add(
					new System.SelectOption(
						contactRec.Id, 
						contactRec.Name
					)
				);
			}//for
		}
	}
	
	//Private Methods
	private void init(){
		accOptions = new new List<System.SelectOption>();
		conOptions = new new List<System.SelectOption>();
	}
}
basha skbasha sk
@Jigarshah thanks for giving the response.Here i'm able to get the accounts list and based on particular account selection getting all contacts.but here my requirement is out of contacts picklist i'm going to pass only one contact to next level for mapping that contact details with other object.Thanks
basha skbasha sk
For example: Salesforce account "Test" it has three related contacts 1,first 2.second 3.third are related contacts to the Test Account.out of three contacts if i select any one particular contact i want to filter that contact.like if i select "third contact" filter only  third contact details.
jigarshahjigarshah
Basha,

I believe once a Contact is selected in the picklist you will have the Record Id of the selected Contact captured in the selectedContactId property from my code snippet above.

Use the below code to identify the Contact record and map its values to another object's fields. Refer the code below with the additional methods to filter the selected Contact record based on the selection within the Contact picklist. Addition to this code are the getSelectedContact() and populateContactDetails() methods.
public with sharing class Picklist{

	public Map<Id, Account> accountIdRecordMap {get; set;}
	public Status__c login1 {get; set;};
	
	public List<System.SelectOption> accOptions{get;set;}
	public Id selectedAccId {get; set;}
	public List<System.SelectOption> conOptions{get;set;}
	public Id selectedContactId {get; set;}
	
	public Contact selectedContact {get; set;}
	public YourCustomObject__c customObjInstance {get; set;}
	
	//Constructor
	public Picklist(ApexPages.StandardController controller){
		this.login1 = (Status__c)controller.getRecord();
		init();
	} 

	//Retrieve most recent 500 Accounts and associated Contacts
	public Map<Id, Account> getAccountsWithContacts(){
	
		if(this.accountIdRecordMap == null){
			
			this.accountIdRecordMap = [Select Id, Name,
										(
											Select Id,
												   name,
												   accountid,
												   FirstName,
												   LastName,
												   email,
												   MobilePhone,
												   MailingCity,
												   MailingState,
												   MailingCountry 
											From Account.Contacts 
										)
									  From Account
									  Order by CreatedDate DESC
									  Limit 500];
		}
		
		return this.accountIdRecordMap;
	}
	
	//Populate account picklist options
	public void getAccountNames(){
		
		if(this.accOptions.size() == 0){
		
			this.accOptions.add(new System.SelectOption('' , '--Select--'));
		
			for(Id accRecId :accountIdRecordMap.keySet()){
				this.accOptions.add(
					new System.SelectOption(
						accRecId, 
						accountIdRecordMap.get(accRecId).Name
					)
				);
			}//for
		} 
	}
	
	//Populate related Contact picklist options
	public void getContactsByAccountId(Id pAccountId){

		this.conOptions.add(new System.SelectOption('' , '--Select--'));
		if(accountIdRecordMap.keySet().containsKey(pAccountId)){

			for(Contact contactRec :((Account)accountIdRecordMap.get(pAccountId)).Contacts){
			
				this.conOptions.add(
					new System.SelectOption(
						contactRec.Id, 
						contactRec.Name
					)
				);
			}//for
		}
	}
	
	//Retrieves the selectedContact Record information based on the selected Account Id
	public void getSelectedContact(){
	
		if(accountIdRecordMap.keySet().containsKey(pAccountId)){

			for(Contact contactRec :((Account)accountIdRecordMap.get(pAccountId)).Contacts){
				if(contactRec.Id == selectedContactId){
					this.selectedContact = contactRec;
				}
			}
		}//if
	}
	
	//Assumes selectedContact is populated with the Contact record information
	public void populateContactDetails(){
	
		if(this.selectedContact <> null){
	
			this.customObjInstance = new YourCustomObject__c(
				CustomField1__c = this.selectedContact.FirstName,
				CustomField2__c = this.selectedContact.LastName,
				CustomField3__c = this.selectedContact.Email,
				CustomField4__c = this.selectedContact.MobilePhone,
				CustomField5__c = this.selectedContact.MailingCity
				.
				.
				//Add all Contact field mappings here
			);
		}
	}
	
	//Private Methods
	private void init(){
		accOptions = new new List<System.SelectOption>();
		conOptions = new new List<System.SelectOption>();
	}
}
This was selected as the best answer
basha skbasha sk
@Jigarshah thanks for giving the response and keep supporting i tried the above code i got one compile time error : Error: Compile Error: Illegal assignment from List<Account> to Map<Id,Account> at line 25 column 18 please check it once .Thanks
jigarshahjigarshah
My bad, update line # 25 with the code snippet below.
this.accountIdRecordMap = new Map<Id, Account>(
				[Select Id, Name,
				 (Select Id,
						 name,
						 accountid,
						 FirstName,
						 LastName,
						 email,
						 MobilePhone,
						 MailingCity,
						 MailingState,
						 MailingCountry 
					From Account.Contacts)
			   From Account
			   Order by CreatedDate DESC
			   Limit 500]);
basha skbasha sk
@jigarshah thanks that issue was resolved but i got one more error : 
Error: Compile Error: Method does not exist or incorrect signature: void containsKey(Id) from the type Set<Id> at line 53 column 40
  at this line    
public void getContactsByAccountId(Id pAccountId){
        this.conOptions.add(new System.SelectOption('' , '--Select--'));
        if(accountIdRecordMap.keySet().containsKey(pAccountId)){  //error at this line 

        
jigarshahjigarshah
Use the below code. There could be possible syntax issues in the above code, which I recommend you verify with the Apex Developer Guide documentation (https://resources.docs.salesforce.com/sfdc/pdf/salesforce_apex_language_reference.pdf).
accountIdRecordMap.containsKey(pAccountId);
basha skbasha sk
@jigarshah thank you so much the apex class working saving but in visualforce pagr i used like this but the account dropdown doesn't display anything please check it once 


vf page : 


<apex:page standardController="Webinar_Attendees_Status__c" extensions="Picklist">
<apex:form>
<apex:pageBlock title="Registration Form">                           
                    Account Names&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                     <apex:selectList value="{!selectedAccId}" size="1">                                 
                        <apex:selectOptions value="{!accOptions}"/>
                        <apex:actionSupport event="onchange" reRender="a"/>
                     </apex:selectList>                  
                     <br/><br/>           
                Related Contacts&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
             <apex:selectList value="{!pAccountId}" size="1"  id="a">
                <apex:selectOptions value="{!conOptions}" />
            </apex:selectList><br/>
            <apex:pageBlockSection >              
            </apex:pageBlockSection>  
       </apex:pageBlock>
       </apex:form>
</apex:page>


Thanks
jigarshahjigarshah
Update the following method within Apex controller as below.
 
//Retrieve most recent 500 Accounts and associated Contacts
	public void getAccountsWithContacts(){
	
		if(this.accountIdRecordMap == null){
			
			this.accountIdRecordMap = new Map<Id, Account>(
				[Select Id, Name,
				(
					Select Id,
						   name,
						   accountid,
						   FirstName,
						   LastName,
						   email,
						   MobilePhone,
						   MailingCity,
						   MailingState,
						   MailingCountry 
					From Account.Contacts 
				)
			  From Account
			  Order by CreatedDate DESC
			  Limit 500]
			);
		}

		this.getAccountNames();
	}

Once done, update your <apex:page> to include an action call to invoke the  getAccountsWithContacts() as shown below.
<apex:page standardController="Webinar_Attendees_Status__c" extensions="Picklist" action="{!getAccountsWithContacts}">
basha skbasha sk
@jigarshah I update the apex class as you suggested now i'm able to get all accounts but if i select any account related contacts doesn't populated please check it once.thanks
jigarshahjigarshah
You will need to use <apex:param component with your picklist to store the selected option Record Id within a controller property.Refer the Visualforce Standard Component Reference (https://resources.docs.salesforce.com/sfdc/pdf/salesforce_pages_developers_guide.pdf)to understand how to use <apex:param> tag within Visualforce.
basha skbasha sk
@Jigarshah thanks for helping me .Here I'm using like this in  Visualforce page please chek it once i tried like this   
                      <apex:actionFunction name="DoFilter" action="{!getContactsByAccountId}" rerender="out" status="loading">
                              <apex:param assignTo="{!conOptions}" value="" name="Contacts List"/>     
                      </apex:actionFunction>

I got some errors please check it once 

Thanks
basha skbasha sk
@Jigarshah thank you so much for your help please help me this is the last step only i have.
basha skbasha sk
@Jigarshah I tried with <apex:param> tag but still it doesn't updated contact list please check it once .
    <apex:actionFunction name="DoFilter" action="{!getContactsByAccountId}" rerender="out" status="loading">
                              <apex:param assignTo="{!conOptions}" value="" name="Contacts List"/>     
                      </apex:actionFunction>

Thanks
jigarshahjigarshah
Update the <apex:param> code as follows.
<apex:param assignTo="{!selectedContactId}" value="document.getElementById('a').value" name="cl"/>