[SalesForce] Error on selecting value from dynamic picklist

I am getting error while selecting value from a dynamic picklist. The picklist values are generated on form load by selecting the distinct values for a field in an object.

Class

   public SET<SelectOption> distinctDomain {get;set;}
   /*To get the distinct values for the picklist for contact - Domain, City, Country*/
   public Set<SelectOption> getDistinctPicklistValues(){
        distinctDomain = new Set<SelectOption>();  
        for(Contact a : [select id,MailingCity, MailingCountry, Domain__c from Contact]){        
            distinctDomain.add(new SelectOption(a.Domain__c.trim(),a.Domain__c.trim()));
        }
        return distinctDomain;
   }

Page

        <apex:outputText value="Pick List" styleClass="outputDec"/>
        <apex:selectList value="{!contactDomain}" multiselect="false" size="1" style="width:159px;">
            <apex:selectOptions value="{!distinctDomain}"/>
                 <apex:actionSupport event="onchange" rerender="contactForm" oncomplete="jsPicklistClear();" action="{!fetchJobs}"/>  
        </apex:selectList> 

The error is thrown in the action support in VF Page. When I remove the action support I am getting no error. Also the code is not entering the function fetchJobs() because of the error thrown in action support.

Error:
j_id0:mainForm:j_id27:j_id31: Validation Error: Value is not valid

Please find the screenshot shown below:

enter image description here

Best Answer

The getter is called each time a form submit occurs. If the records that are queried change between form submits, you can cause this error to occur.

I would suggest that you only initialize the list inside the constructor or an action method, and always validate that the currently selected value matches one of the options from the list of options you generate.

Modifying a list like this in a getter or setter method is a sure-fire way to get unexpected results.

Finally, use should use a list instead of a set. The unordered nature of sets might also cause this problem, but I'd have to test that.

Query all the domains into a set of strings, then generate the list of select options from that set.

Related Topic