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
Ravi Rao ArrabelliRavi Rao Arrabelli 

Pass the Selected Values from Multi-select in Visualforce to the Custom Controller

Hi All,
I'm building a custom search, in which multi-select is one of the filter criteria. I have built the following code and used dynamic soql for this purpose:

vf page code:
<apex:selectlist multiselect="True" size="4" value="{!businessLines}" >
         <apex:selectOptions value="{!busLinesLs}" />
 </apex:selectlist>

Custom Controller Code:
public List<string> businessLines{get;set;}
public List<SelectOption> busLinesLs{
        get{
            if(busLinesLs==null){
            busLinesLs = new List<SelectOption>();    
                Schema.DescribeFieldResult field = CustomObj__c.CustomField__c.getDescribe();
                for (Schema.PickListEntry f: field.getPickListValues())
                    busLinesLs.add(new SelectOption(f.getValue(),f.getLabel()));
            }
            return busLinesLs;
        }
        set;
    }

 if(!businessLines.isempty()){
            boolean flag = False;
            system.debug('----------'+ businessLines);
            soqlStr += 'AND (';
            for(String str: businessLines){
                if(flag){
                    soqlStr += ' OR ';
                }
                soqlStr += ' CustomField__c INCLUDES (\''+str+'\')';
                flag = True;
            }
            soqlStr += ')';
        }

I'm able to populate the picklist values in the page, but I think the highlighted values are not getting passed back to the controller. Can someone, please help me.
Thanks in Advance.
Mahesh DMahesh D
Hi Ravi,

Please find an example here:
 
<!-- Page: -->
<apex:page controller="sampleCon">
    <apex:form>
        <apex:selectList value="{!countries}" multiselect="true">
            <apex:selectOptions value="{!items}"/>
        </apex:selectList><p/>

        <apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/>
    </apex:form>

    <apex:outputPanel id="out">
        <apex:actionstatus id="status" startText="testing...">
            <apex:facet name="stop">
                <apex:outputPanel>
                    <p>You have selected:</p>
                    <apex:dataList value="{!countries}" var="c">{!c}</apex:dataList>
                </apex:outputPanel>
            </apex:facet>
        </apex:actionstatus>
    </apex:outputPanel>
</apex:page>
            
/*** Controller: ***/
    public class sampleCon {
        String[] countries = new String[]{};
            
        public PageReference test() {
            return null;
        }
            
        public List<SelectOption> getItems() {
            List<SelectOption> options = new List<SelectOption>();
            options.add(new SelectOption('US','US'));
            options.add(new SelectOption('CANADA','Canada'));
            options.add(new SelectOption('MEXICO','Mexico'));
            return options;
        }
            
        public String[] getCountries() {
            return countries;
        }
            
        public void setCountries(String[] countries) {
            this.countries = countries;
        }
    }

Please do let me know if it helps.

Regards,
Mahesh
Mahesh DMahesh D
Hi Ravi,

If possible please paste your full code and also use the above panel to copy the code (< >) so that it will be easy to understand the code.

Regards,
Mahesh
Ravi Rao ArrabelliRavi Rao Arrabelli
CUSTOM CONTROLLER- Code is big. Highlighted portion of code would be of your concern.

public class SearchPageController {
    public searchPageController(ApexPages.StandardController controller){
        
    }
    
    public String keywords{get;set;}
    public Integer minSeats{get;set;}
    Public Integer maxSeats{get;set;}
    public Integer minEmp{get;set;} 
    public Integer maxEmp{get;set;}
    public transient String depKeyword{get;set;}
    public Boolean apiUse{get;set;}
    public List<Account> accounts{get;set;}
    public List<Id> accIdLs;
    public List<Customer_Profile__c> custProfLs;
    public string soqlStr;
    public string soqlQuery;
    public string soslStr;
    public string soslQuery;
    public string coreApps;
    public List<string> businessLines{get;set;}
    
    public void runQuery(){
        
        soqlQuery = 'SELECT Id, name, Account__c, Total_Seats__c, Industry__c, Business_Objectives__c, ' +
            'Other_Use_Case_Description__c, Adoption_Program_Notes__c, Additional_Notes__c, Core_Mobile_Apps_in_Use__c, ' +
            'Core_Desktop_Apps__c, Other_Mobile_Apps_in_Use__c, Other_Desktop_Apps__c FROM Customer_Profile__c  WHERE ' +
            soqlStr;
        system.debug('----------soqlQuery: '+soqlQuery);
        
        custProfLs = new List<Customer_Profile__c>();
        accounts = new List<Account>();
        accIdLs = new List<Id>();
        Set<Id> keyCustIds = new set<Id>();
        boolean sosl = False;
        if(!string.isBlank(soslStr)){
            sosl = True;
            soslQuery = 'FIND \''+soslStr+ '\' IN ALL FIELDS Returning Customer_Profile__c(Id,Name)';
            system.debug('---------soslQuery: '+ soslQuery);
            List<List<sObject>> keyResults = search.query(soslQuery);
            List<Customer_Profile__c> keyCustProfLs = new List<Customer_Profile__c>((List<Customer_Profile__c>)keyResults[0]);
            for(Customer_Profile__c keyCp: keyCustProfLs){
                keyCustIds.add(keyCp.Id);
            }
        }
        
        for(Customer_Profile__c custp:Database.query(soqlQuery)){
            if(!string.isblank(depKeyword)){
                if((custp.Business_Objectives__c != null && custp.Business_Objectives__c.contains(depKeyword)) || (custp.Other_Use_Case_Description__c != null && custp.Other_Use_Case_Description__c.contains(depKeyword)) || (custp.Adoption_Program_Notes__c != null && custp.Adoption_Program_Notes__c.contains(depKeyword)) || (custp.Additional_Notes__c != null && custp.Additional_Notes__c.contains(depKeyword))){
                    system.debug('---------Entering Loop 1');
                    if(!string.isblank(coreApps)){
                        if(custp.Core_Mobile_Apps_in_Use__c == coreApps || (custp.Other_Mobile_Apps_in_Use__c != null && custp.Other_Mobile_Apps_in_Use__c.contains(coreApps)) || custp.Core_Desktop_Apps__c == coreApps || (custp.Other_Desktop_Apps__c != null && custp.Other_Desktop_Apps__c.contains(coreApps))){
                            if(!sosl || (!keyCustIds.isEmpty() && keyCustIds.contains(custp.Id))){ custProfLs.add(custp);}
                        }
                    }else if(!sosl || (!keyCustIds.isEmpty() && keyCustIds.contains(custp.Id))){ custProfLs.add(custp);}
                    
                }
            }else if(!string.isblank(coreApps)){
                    if(custp.Core_Mobile_Apps_in_Use__c == coreApps || (custp.Other_Mobile_Apps_in_Use__c != null && custp.Other_Mobile_Apps_in_Use__c.contains(coreApps)) || custp.Core_Desktop_Apps__c == coreApps || (custp.Other_Desktop_Apps__c != null && custp.Other_Desktop_Apps__c.contains(coreApps))){
                        if(!sosl || (!keyCustIds.isEmpty() && keyCustIds.contains(custp.Id))){ custProfLs.add(custp);}
                    }
                }else if(!sosl || (!keyCustIds.isEmpty() && keyCustIds.contains(custp.Id))){ custProfLs.add(custp);}
        }
        
        //system.debug('---------AccIds: '+ accIdLs);
        if(!custProfLs.isEmpty()){
            for(customer_profile__c cp: custProfLs){
                Id accId = cp.Account__c;
                accIdLs.add(accId);
            }
        }else{
            ApexPages.addMessage(new ApexPages.message(ApexPages.Severity.ERROR,'No Such Customer profile Records found!'));
        }
        
        system.debug('-----------AccIdls: ' + accIdLs);
        
        accounts = [Select Id,Name,Total_Seats_Sold__c,Employees_verified__c, Box_Industry__c from Account WHERE Id IN :accIdLs];
    }
    
    public Pagereference runSearch(){
        Map<String,String> params = ApexPages.currentPage().getParameters();
        string useCase = params.get('useCase');
        //string businessLines = params.get('businessLines');
        string integrations = params.get('integrations');
        string prvSol = params.get('prvSol');
        string conSol = params.get('conSol');
        string csIndustry = params.get('csIndustry');
        coreApps = params.get('coreApps');
        
        
        //if(maxEmp==0){ maxEmp= 10000000;}
        //if(maxseats==0){ maxSeats= 10000000;}
        
        soqlStr = 'API_in_Use__c = '+apiUse; //'Total_Seats__c > '+minSeats+' AND Total_Seats__c < '+maxSeats+' AND API_in_Use__c = '+apiUse;
        
        if(minSeats != 0){
            soqlStr += ' AND Total_Seats__c > '+minSeats;
        }
        if(maxSeats != 0){
            soqlStr += ' AND Total_Seats__c < '+maxSeats;
        }
        if(!string.isblank(useCase)){
            soqlStr += ' AND (Primary_Use_Case__c = \''+useCase+'\' OR Secondary_Use_Case__c =\''+useCase+'\')';
        }
        system.debug('----------'+ businessLines);
        if(!businessLines.isempty()){
            boolean flag = False;
            system.debug('----------'+ businessLines);
            //List<String> blinesLs = businessLines.split(',');
            soqlStr += 'AND (';
            for(String str: businessLines){
                if(flag){
                    soqlStr += ' OR ';
                }
                soqlStr += ' Lines_of_Business_Using_Box__c INCLUDES (\''+str+'\')';
                flag = True;
            }
            soqlStr += ')';
        }
        //if(!string.isblank(coreApps)){ soqlStr += ' AND Core_Desktop_Apps__c INCLUDES (\''+coreApps+'\')';}
        
        if(!string.isblank(integrations)){
            soqlStr += ' AND Integrations_Completed__c INCLUDES (\''+integrations+'\')';
        }
        if(!string.isblank(prvSol)){
            soqlStr += ' AND Previous_Solution__c INCLUDES (\''+prvSol+'\')';
        }
        if(!string.isblank(conSol)){
            soqlStr += ' AND Concurrent_Solution__c INCLUDES (\''+conSol+'\')';
        }
        if(!string.isblank(csIndustry)){
            soqlStr += ' AND Industry__c = \''+csIndustry+'\'';
        }
        soslStr = '';
        if(!string.isEmpty(keyWords)){
            boolean flag = False;
            List<string> keyWordsLs = keyWords.split(',');
            for(string str:keyWordsLs){
                if(flag){
                    soslStr += ' AND ';
                }
                soslStr += str;
                flag = True;
            }
            system.debug('----------soslStr: '+ soslStr);
        }
        
        runQuery();
        return null;
    }
    
    public List<String> csIndustryLs{
        get{
            if(csIndustryLs==null){
            csIndustryLs = new List<String>();    
                Schema.DescribeFieldResult field = Customer_Profile__c.Industry__c.getDescribe();
                for (Schema.PickListEntry f: field.getPickListValues())
                    csIndustryLs.add(f.getLabel());
            }
            return csIndustryLs;
        }
        set;
    }
    
    public List<SelectOption> busLinesLs{
        get{
            if(busLinesLs==null){
            busLinesLs = new List<SelectOption>();    
                Schema.DescribeFieldResult field = Customer_Profile__c.Lines_of_Business_Using_Box__c.getDescribe();
                for (Schema.PickListEntry f: field.getPickListValues())
                    busLinesLs.add(new SelectOption(f.getValue(),f.getLabel()));
            }
            return busLinesLs;
        }
        set;
    }
    
    public List<SelectOption> useCaseLs{
        get{
            if(useCaseLs==null){
                useCaseLs = new List<SelectOption>();
                Schema.DescribeFieldResult field = Customer_Profile__c.Primary_Use_Case__c.getDescribe();
                for (Schema.PickListEntry f: field.getPickListValues())
                    useCaseLs.add(new SelectOption(f.getValue(),f.getLabel()));
            }
            return useCaseLs;
        }
        set;
    }
    
    public List<String> coreAppsLs{
        get{
            if(coreAppsLs==null){
            coreAppsLs = new List<String>();    
                Schema.DescribeFieldResult field = Customer_Profile__c.Core_Desktop_Apps__c.getDescribe();
                for (Schema.PickListEntry f: field.getPickListValues())
                    coreAppsLs.add(f.getLabel());
                
                Schema.DescribeFieldResult field1 = Customer_Profile__c.Core_Mobile_Apps_in_Use__c.getDescribe();
                for (Schema.PickListEntry f: field1.getPickListValues())
                    coreAppsLs.add(f.getLabel());
            }
            return coreAppsLs;
        }
        set;
    }
    
    public List<String> integrationLs{
        get{
            if(integrationLs==null){
            integrationLs = new List<String>();    
                Schema.DescribeFieldResult field = Customer_Profile__c.Integrations_Completed__c.getDescribe();
                for (Schema.PickListEntry f: field.getPickListValues())
                    integrationLs.add(f.getLabel());
            }
            return integrationLs;
        }
        set;
    }
    
    public List<String> prvSolLs{
        get{
            if(prvSolLs==null){
            prvSolLs = new List<String>();    
                Schema.DescribeFieldResult field = Customer_Profile__c.Previous_Solution__c.getDescribe();
                for (Schema.PickListEntry f: field.getPickListValues())
                    prvSolLs.add(f.getLabel());
            }
            return prvSolLs;
        }
        set;
    }
    
    public List<String> conSolLs{
        get{
            if(conSolLs==null){
            conSolLs = new List<String>();    
                Schema.DescribeFieldResult field = Customer_Profile__c.Concurrent_Solution__c.getDescribe();
                for (Schema.PickListEntry f: field.getPickListValues())
                    conSolLs.add(f.getLabel());
            }
            return conSolLs;
        }
        set;
    }
    
}

 
Ravi Rao ArrabelliRavi Rao Arrabelli
VF Page is as below: Again code is big. Please, check the highlighted portion.
Also, tried to copy the code through the (<>) tab.. but its still not better.
 
<apex:page standardController="Opportunity" Extensions="SearchPageController" sidebar="false" docType="html-5.0">
    <apex:form >
        <apex:pageMessages id="errors" />
        <apex:pageblock mode="edit" id="block" title="Search Criteria">
            <apex:commandButton value="Search" onclick="doSearch()" reRender="none" />
            
            <script type="text/javascript">
            function doSearch(){
                searchServer(
                    document.getElementById("useCase").options[document.getElementById("useCase").selectedIndex].value,
                    document.getElementById("coreApps").options[document.getElementById("coreApps").selectedIndex].value,
                    document.getElementById("integrations").options[document.getElementById("integrations").selectedIndex].value,
                    document.getElementById("prvSol").options[document.getElementById("prvSol").selectedIndex].value,
                    document.getElementById("conSol").options[document.getElementById("conSol").selectedIndex].value,
                    document.getElementById("csIndustry").options[document.getElementById("csIndustry").selectedIndex].value
                    );
                }
            </script>
            
            <apex:actionFunction name="searchServer" action="{!runSearch}" reRender="results,debug,errors">
                <apex:param name="useCase" value="" />
                
                <apex:param name="coreApps" value="" />
                <apex:param name="integrations" value="" />
                <apex:param name="prvSol" value="" />
                <apex:param name="conSol" value="" />
                <apex:param name="csIndustry" value="" />
            </apex:actionFunction>
            
            <table cellpadding="4" cellspacing="4" >
                <tr>
                    <td style="font-weight:bold;">Keywords with Commas<br/>
                        <apex:input type="text" value="{!keyWords}" />
                    </td>
                    <td style="font-weight:bold;">Min Seats<br/>
                        <apex:input type="number" value="{!minSeats}" />    
                    </td>
                    <td style="font-weight:bold;">Max Seats<br/>
                        <apex:input type="number" value="{!maxSeats}"/>    
                    </td>
                    <td style="font-weight:bold;">Min Employees<br/>
                        <apex:input type="number" value="{!minEmp}" />
                    </td>
                    <td style="font-weight:bold;">Max Employees<br/>
                        <apex:input type="number" value="{!maxEmp}" />    
                    </td>
                    <td style="font-weight:bold;">Deployment Keyword<br/>
                        <apex:input type="text" value="{!depKeyword}" />
                    </td>
                    <td style="font-weight:bold;">API in Use<br/>
                        <apex:inputCheckbox value="{!apiUse}" />
                    </td>
                </tr>
            </table>
            <table cellpadding="4" cellspacing="4">
                <tr>
                    <td style="font-weight:bold;">Use Case<br/>
                        <apex:selectlist multiselect="false" size="1">
                            <apex:selectOption itemValue="" ></apex:selectOption>
                            <apex:selectOptions value="{!useCaseLs}" />
                        </apex:selectlist>
                    </td>
                    <!--<td style="font-weight:bold;">Use Case<br/>
                        <select id="useCase" multiselect="True">
                            <option value=""></option>
                            <apex:repeat value="{!useCaseLs}" var="useCs">
                                <option value="{!useCs}">{!useCs}</option>
                            </apex:repeat>
                        </select>      
                    </td> --->
                    <td style="font-weight:bold;">Lines of Business<br/>
                        <apex:selectlist multiselect="True" size="4" value="{!businessLines}" >
                            <apex:selectOptions value="{!busLinesLs}" />
                        </apex:selectlist>
                    </td>
                    <td style="font-weight:bold;">Core Box Apps<br/>
                        <select id="coreApps" >
                            <option value=""></option>
                            <apex:repeat value="{!coreAppsLs}" var="coreApps">
                                <option value="{!coreApps}">{!coreApps}</option>
                            </apex:repeat>
                        </select>      
                    </td>
                    <td style="font-weight:bold;">Integrations<br/>
                        <select id="integrations" >
                            <option value=""></option>
                            <apex:repeat value="{!integrationLs}" var="int">
                                <option value="{!int}">{!int}</option>
                            </apex:repeat>
                        </select>      
                    </td>
                    <td style="font-weight:bold;">Previous Solution<br/>
                        <select id="prvSol" >
                            <option value=""></option>
                            <apex:repeat value="{!prvSolLs}" var="prev">
                                <option value="{!prev}">{!prev}</option>
                            </apex:repeat>
                        </select>      
                    </td>
                    <td style="font-weight:bold;">Concurrent Solution<br/>
                        <select id="conSol" >
                            <option value=""></option>
                            <apex:repeat value="{!conSolLs}" var="conSol">
                                <option value="{!conSol}">{!conSol}</option>
                            </apex:repeat>
                        </select>      
                    </td>
                </tr>
            </table>
            
            <table cellpadding="4" cellspacing="4">
                <tr>
                    <td style="font-weight:bold;">CS Industry<br/>
                        <select id="csIndustry" >
                            <option value=""></option>
                            <apex:repeat value="{!csIndustryLs}" var="csind">
                                <option value="{!csind}">{!csind}</option>
                            </apex:repeat>
                        </select>      
                    </td>
                </tr>
            </table>
            <apex:commandButton value="Search" onclick="doSearch()" reRender="none" />
            
        </apex:pageblock>
        
        <apex:pageblock id="results" title="Results" >
            <apex:pageBlockTable value="{!accounts}" var="acc">
                <apex:column value="{!acc.Name}"/>
                <apex:column value="{!acc.Total_Seats_Sold__c}" />
                <apex:column value="{!acc.Employees_verified__c}" />
                <apex:column value="{!acc.Box_Industry__c}" />
            </apex:pageBlockTable>
        </apex:pageblock>
        
    </apex:form>
</apex:page>

 
Ravi Rao ArrabelliRavi Rao Arrabelli
Hi Mahesh,
The above are the complete codes and you can search for the part of the code which I posted in my first post (question).

 
Ravi Rao ArrabelliRavi Rao Arrabelli
@Mahesh...
I figured it out.. I was collecting the selected values (for another Picklist) through the javascript instead of storing directly in a custom control variable