[SalesForce] Access multi – select picklist selected values in Apex Class

I have the following multi-select picklist code in my Visualforce page

<apex:selectList styleClass="form-control evemin" id="testid" size="3" multiselect="true" value="{!testVariable}" >
        <apex:selectOption itemLabel="test1" itemValue="test1"/>
        <apex:selectOption itemLabel="test2" itemValue="test2"/>
        <apex:selectOption itemLabel="test3" itemValue="test3"/>
</apex:selectList>

testvariable is a String array variable in my apex class. Is this a proper way to pass the value in Controller. What I can see is that it does not take the selected option to Apex class in this process. Is there any other way to do this

Best Answer

Refer this link apex:selectList, which is the correct way to handle multi-select picklist

<!-- 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[]{};
        //If multiselect is false, countries must be of type String
        //String countries;

        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() {
            //If multiselect is false, countries must be of type String
            return countries;
        }

        public void setCountries(String[] countries) {
            //If multiselect is false, countries must be of type String
            this.countries = countries;
        }
    }
Related Topic