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
CodySechelskiCodySechelski 

Getting the Selected value of a SelectList in the controller.

Hi,

 

I have been struggling with this all day. I'm just trying to get the value that was selected in a SelectList, and use it to do some DML stuff. I don't need to do an ajax request and print back to the screen (that seems to be what all of the code snippets out there are doing).

 

Here's the VF page:

 

<apex:page controller="SelectPricebookController" action="{!pageLoad}" showHeader="false" sidebar="false" title="Select Price List">
    <div class="opportunityTab" style="margin:15px;">
        <apex:form id="TheForm">
        <apex:sectionHeader title="Opportunity" subtitle="Select Price List"/>
        <div class="bDescription"></div>
        <apex:pageBlock >
            <apex:pageBlockSection >
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Price Book" for="ddlPriceBooks"/>
                    <apex:selectList id="ddlPriceList" size="1" multiselect="false" value="{!priceList}" title="Select a Price List">
                    	<apex:selectOptions value="{!lists}"/>
                    </apex:selectList>
                </apex:pageBlockSectionItem>
            </apex:pageBlockSection>
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Select" action="{!savePriceList}" immediate="true"/>
            </apex:pageBlockButtons>
        </apex:pageBlock> 
        </apex:form>
    </div>
</apex:page>

 

 

and here's the controller:

 

public with sharing class SelectPricebookController {


    private Opportunity opp;
    private Account acc;
    private Boolean isDirect = true;
    private String[] optionsToAdd;

    public String pList;
    
    
    public String getPriceList() {
        return pList;
    }

   public void setPriceList(String p) {
       System.Debug('================================== Set priceList: ' + p);
        this.pList = p;
    }
    
    public PageReference pageLoad(){
        //Get the Opportunity based on the query param
        String OppID;
        if (ApexPages.currentPage().getParameters().get('OppID') != null){
            OppID = ApexPages.currentPage().getParameters().get('OppID');
            
            opp = [Select Purchase_Channel_Account__c, Name, AccountId, Price_List__c from Opportunity where ID = :OppID Limit 1];
            
            //Gets the correct account. If the Purchase Channel account is null,
            //it will get the primary account.
            //If not, it will get Purchase Channel Account
            if (opp.Purchase_Channel_Account__c != null){
                acc = [Select NAME, Available_Direct_Price_Lists__c, Available_Channel_Price_Lists__c from Account where ID = :opp.Purchase_Channel_Account__c  Limit 1];
                isDirect = false;
            }
            else{
                acc = [Select NAME, Available_Direct_Price_Lists__c, Available_Channel_Price_Lists__c from Account where ID = :opp.AccountId  Limit 1];
            }

            System.debug('Opportunity ID======================================================> ' + opp.id);
            System.debug('Accout ID======================================================> ' + acc.id);
            
            //Gets the available price lists from the account
            String[] lists;
        
            if(isDirect){
                lists = acc.Available_Direct_Price_Lists__c.split(';');
            }
            else{
                lists = acc.Available_Channel_Price_Lists__c.split(';');
            }
                        
            //If there is only one option, just update the opp and redirect
            //Else, show the user a list to pick from
            if(lists.size() == 1){
                optionsToAdd = lists;
                return updateOpp(lists[0]);
            }
            else{
                optionsToAdd = lists;
                return null;
            }
        }
        else{
            //TODO: Handle Exception
            return null;
        }
    }
    
    public List<SelectOption> getLists(){
        List<SelectOption> options = new List<SelectOption>();
        
        for (Integer i = 0; i < optionsToAdd.size(); i++){
            System.debug('Options======================================================> ' + optionsToAdd[i]);
            options.add(new SelectOption(optionsToAdd[i],optionsToAdd[i]));
        }
        
        return options;
    }
    
    public PageReference savePriceList(){
        System.debug('============== pricelist: ' + pList);
        return updateOpp(pList);
    }
    
    private PageReference updateOpp(String p){
        opp.Price_List__c = p;
        System.debug('====================== Updated pricelist to: ' + p);
        update opp;
        
        PageReference pageRef = new PageReference('/' + opp.Id);
        pageRef.setRedirect(true);
        return pageRef;
    }
}

 

 

As you can see, I have a public string variable to hold the value, a getter and a setter. Then I try to use the variable in the savePriceList method. However, it's always null.

 

Thanks for the help!

sfdc guy.ax723sfdc guy.ax723

Cody,

Try taking the immediate="true" out of your apex:commandButton.

 

<apex:commandButton value="Select" action="{!savePriceList}"/>
CodySechelskiCodySechelski

Thanks, but when I take that off, The button will not process the action, It just refreshes the page.

sravusravu

Try using <apex:param/> component.

But instead of using <apex:commandButton> use <apex:commandLink>. The code will look like:

 

<apex:commandLink value="Select" action="{!savePriceList}">

       <apex:param name="selectVal" value="<Give the value selected by the user>" assignTo="{!selVal}"/>

</apex:CommandLink>

 

You can always use styling to make it look like a button if you really have to have a button there

And in the Controller,

 

public String selVal {get;set;}

 

Now you can use selval in the controller to perform DML operations.

 

Let me know if you face any difficulties.............

DaveHagmanDaveHagman

I have been struggling with this exact same issue all day. You're also correct in that all the documentation just shows you how to re render some part of the page based on the selection but that is not what I need to do either. I need to do the same thing as you, just get the label data of whatever item is selected. It is harder than it should be.

Pradeep_NavatarPradeep_Navatar

Tryout the sample code given below to get selected value of selectlist and pass it in to controller :

 

<apex:form>
<apex:selectList value="{!ListProfile}"  size="1"  style="display:none" onchange="FetchData(this.options[this.selectedIndex].text);" >
<apex:selectOptions value="{!Pickvalues}"></apex:selectOptions>
</apex:selectList>
<apex:actionFunction action="{!GivePortalAccess}" reRender="refreshdt,msgerror">
<apex:param assignTo="{!ListProfile}" value=""/>
</apex:actionFunction>                                 
</apex:form>

DaveHagmanDaveHagman

Does the FetchData() function put the text of the selected item into the {!ListProfile} variable in the controller?

DaveHagmanDaveHagman

That worked! Thank you so much for that information! Worked like a charm. Why can't that be in ANY of the documentation Sales Force?!?!

SoozeeSoozee

Is it possible to get the selected value of a different select list on change?

SoozeeSoozee

Hi - I'd like to elaborate on my question...

I have three drop-down fields in my VF page.  The combination of all three values will populate a SOQL Query.  For instance:

 

<apex:selectList id="owner" size="1" value="{!letterowner}" onChange="DoFilter(this.options[this.selectedIndex].text);">
                        <apex:selectOption itemValue="My Letters" itemLabel="My Letters"/>
                        <apex:selectOption itemValue="All Letters" itemLabel="All Letters"/>
                </apex:selectList>
   			</td>
   			<td>  
   				<b>Type:</b>&nbsp;&nbsp; <apex:selectList id="type" size="1" value="{!lettertype}" onChange="DoFilter(this.options[this.selectedIndex].text);">
            	<apex:selectOptions value="{!types}"/>
   				</apex:selectList><p/>
   			</td>
   			<td>
   				<b>Status:</b> &nbsp;&nbsp;<apex:selectList id="status" size="1" value="{!letterstatus}" onChange="DoFilter(this.options[this.selectedIndex].text);">
            	<apex:selectOptions value="{!statuses}"/>
   				</apex:selectList>
   			</td>

 And then, I send the params to the controller:

 

<apex:actionFunction name="DoFilter" action="{!doFilter}" rerender="out" status="loading">
     <apex:param assignTo="{!letterowner}" value="" name="letterowner"/>
     <apex:param assignTo="{!lettertype}" value="" name="lettertype"/>
     <apex:param assignTo="{!letterstatus}" value="" name="letterstatus"/>
   </apex:actionFunction>

 However, the only parameter that gets sent is the value of the drop down being changed.  How do I reference the values of the other drop downs on the page?

I tried referencing them by substituting 'this' with the id of the drop down, but it didn't work.  Help?!

 

<apex:selectList id="owner" size="1" value="{!letterowner}" onChange="DoFilter(this.options[this.selectedIndex].text, type.options[type.selectedIndex].text,status.options[status.selectedIndex].text);">
                        <apex:selectOption itemValue="My Letters" itemLabel="My Letters"/>
                        <apex:selectOption itemValue="All Letters" itemLabel="All Letters"/>
                </apex:selectList>
   			</td>
SoozeeSoozee

I got this to work by getting the field name of each select option at the onChange event and sent the field name to a javascript function that took the field name and got the selected value.

 

   			<apex:selectList id="ltrOwner" size="1" value="{!letterowner}" onChange="getSelected('{!$Component.ltrowner}','{!$Component.ltrType}','{!$Component.ltrStatus}');">
                        <apex:selectOption itemValue="My Letters" itemLabel="My Letters"/>
                        <apex:selectOption itemValue="All Letters" itemLabel="All Letters"/>
                </apex:selectList>
  

 and the javascript

 

function getSelected(owner,type,status){
	  var letterowner = document.getElementById(owner).options[document.getElementById(owner).selectedIndex].text;
	  var lettertype = document.getElementById(type).options[document.getElementById(type).selectedIndex].text;
	  var letterstatus = document.getElementById(status).options[document.getElementById(status).selectedIndex].text;
	  DoFilter(letterowner,lettertype,letterstatus);
	  
  }

 And then DoFilter actionFunction

 <apex:actionFunction name="DoFilter" action="{!doFilter}" rerender="out" status="loading">
     <apex:param assignTo="{!letterowner}" value="" name="letterowner"/>     
     <apex:param assignTo="{!lettertype}" value="" name="lettertype"/>
     <apex:param assignTo="{!letterstatus}" value="" name="letterstatus"/>
   </apex:actionFunction>

 

jassjass

How to redirect a page on selecting a select List option value?