0

VisualForce Page

<apex:page controller="dynamicpicklistcontroller" sidebar="false" >
<apex:form >
    <apex:pagemessages />
<apex:sectionHeader title="Colleges" subtitle="at UGA"/>
<apex:pageblock >
<apex:pageBlockSection title="Dynamic picklist" columns="1">
      <apex:pageblocksectionItem >
          <apex:outputlabel value="Colleges" for="values" />
          <apex:selectList value="{!listofacc}" size="1" id="values">
              <apex:actionSupport event="onchange" reRender="newvalue" />
              <apex:selectOptions value="{!colleges}"/>
          </apex:selectList>
      </apex:pageblocksectionItem>                                        
             <div style="position:relative;left:75px;">             
                  <apex:outputlabel value="New value" for="newval" />
                  <apex:inputText value= "{!newcollege}" id="newval"/>
                  <apex:commandbutton action="{!saverec}" value="Add!"/>
             </div>                            
  </apex:pageBlockSection>
</apex:pageblock>
</apex:form>
</apex:page>

Apex Class

public class dynamicpicklistcontroller {
public List<SelectOption> statusOptions { get;set; }
public List<College__c> listofacc{get;set;}// You can use any sObject for which you want to apply the search
 

public List<SelectOption> getcolleges()
{
  List<SelectOption> options = new List<SelectOption>();
  List<College__c> collegelist = new List<College__c>();
  collegelist = [Select Name FROM College__c ];
  options.add(new SelectOption('--None--','--None--'));
  for (Integer j=0;j<collegelist.size();j++)
  {
      options.add(new SelectOption(collegelist[j].Name,collegelist[j].Name));
  }
  return options;
}

public String newcollege {get; set;}
public void saverec() //saves a record to the list
{      
    //this is the issue area
    List<College__c> newcoll = new List<College__c>();
    newcoll.add(new College__c(Name = newcollege));
    insert newcoll;
    
} 
    
    
}

Have an issue saving the new value, tried many ways to convert the String into a list but ultimately failed. This is my first time using Apex so need some help finding out why it's not working. I tried to look up solutions online but didn't succeed in solving the issue.

1 Answer 1

0

When the apex:selectList multiselect attribute is set to false, then the value attribute must be of type String (see here). In your code example the apex:selectList has a size attribute of 1, which implicitly sets the multiselect value to false.

As a result, the Invalid conversion error is thrown because listofacc property returns List<College__c when it should return type String as described above.

Changing the property return value to String will resolve the error:

public String listofacc{get;set;}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .