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
SayasoniSayasoni 

Help with setting default Picklist value.

I have a controller which redirects a user to different visualforce pages depending on the picklist value selected.However, its not working exactly as expected. The 'Add to contact' option appears as the default value thus when i select on 'Add to Associate' , it opens the 'Addtocontact' page rather than opening 'Addtoassociate' page.

How do i set a default picklist value something like 'Select option to Add to' ,then get the 'Add to contact' & 'Add to Associate' working properly as expected.

Below is my controller and part of the visualforce page.

 

public class redirectonthebasisofpicklist
 {

public list<selectoption>item{get;set;}

public string picklistvalue{get;set;}

public redirectonthebasisofpicklist()
{
    item=new list<selectoption>();
    item.add(new selectoption('Addtocontact','Add to contact'));
    item.add(new selectoption('AddtoAssociate','Add to Associate'));

}
public pagereference redirect()
{
    PageReference pageRef= new PageReference('/apex/'+picklistvalue);
    pageRef.setredirect(true);
    return pageRef;

}
}

 

 

 

<apex:page controller="redirectonthebasisofpicklist" >
 <Apex:form >
     <apex:selectList value="{!picklistvalue}" size="1" >

     <Apex:selectOptions value="{!item}"/>

    <apex:actionSupport event="onchange" action="{!redirect}" />    

     </apex:selectList>

 </Apex:form>
</apex:page>

 

bob_buzzardbob_buzzard

You should just be able to add another option to the list:

 

public redirectonthebasisofpicklist()
{
    item=new list<selectoption>();
item.add(new selectoption('-- None --', '-- None --')); item.add(new selectoption('Addtocontact','Add to contact')); item.add(new selectoption('AddtoAssociate','Add to Associate')); }

 

and then check the user has selected one in the redirect method:

 

public pagereference redirect()
{
    PageReference pageRef=null;
    if (picklistvalue=='-- Please Choose --')
    {
       // could add an error or warning message here
    }
    else
    {
       pageRef= new PageReference('/apex/'+picklistvalue);
       pageRef.setredirect(true);
    }

    return pageRef;
}

 

 

 

SayasoniSayasoni

Hi Bob,

Thanks for your reply.However.this solution seems to work perfectly well with a simple scenario like the one above but i can't seem to make it work with the following piece of code: All options selected tend to return the error message part.

public PageReference addToSelected() {
    id = System.currentpagereference().getparameters().get('id');
      List<UnresolvedEmail__c> selectedEmails = new List<UnresolvedEmail__c>();
        //We will cycle through our list of cUnresolvedEmails and will check to see if the selected property is set to true, if it is we add the UnresolvedEmail to the selectedEmails list
        for(cUnresolvedEmails cUnr : unResolvedList) {
            if(cUnr.selected == true) {
                selectedEmails.add(cUnr.unresolvedeml);
            }
        }
		  // Now we have our list of selected contacts to add to:
        System.debug('These are the selected Emails...');
        for(UnresolvedEmail__c unresolvedeml : selectedEmails) {
            system.debug(unresolvedeml);   
              PageReference pageRef=null;
		    	if (picklistvalue=='None')
		    	{
		       ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Select an option to proceed!'));
		    	}   
		    	else 
		    	{
             pageRef= new PageReference('/apex/'+picklistvalue+'?id='+unresolvedeml.id);
		     pageRef.setredirect(true);            
           }
             return pageRef;
           
    }
      return null;
    } 
    

 Note: If i don't iclude the return null; part at the end, i get this error: Save error: Non-void method might not return a value or might have statement after a return statement. on the bold line section.

bob_buzzardbob_buzzard

If they all return the error message, that implies that the value isn't being set correctly in the controller.  Can you post the VF?

SayasoniSayasoni

Here is the whole of my visualforce page: The bold section is the one for handling selectList.

<apex:page controller="UnresolvedEmailsController" >
<style  type="text/css">
  p {color:red }
  </style>
  <p> <b> Please select a record before performing any action!</b> </p>
<apex:form >
  <apex:pageBlock title="Unresolved Emails" mode="edit" >
  <apex:pageMessages /> <!-- this is where the error messages will appear -->
  
    <apex:pageBlockButtons >
                <apex:commandButton value="Delete Selected Emails" action="{!processSelected}" />
                <apex:commandButton value="Ignore Selected Emails" action="{!ignoreSelected}" />
    </apex:pageBlockButtons>
                
 <apex:pageBlockTable value="{!unresolvedEmail}" var="Emails" >
                <apex:column >
                <apex:facet name="header"> 
                <apex:inputCheckbox >
                <apex:actionSupport event="onclick"  onsubmit="checkAll(this)" rerender="Selected_email"/>
                </apex:inputCheckbox>
                </apex:facet>
                <!-- This is our selected Boolean property in our wrapper class -->
                <apex:inputCheckbox value="{!Emails.selected}" id="checkedone" >
                <apex:actionSupport event="onclick" rerender="Selected_email" />
                </apex:inputCheckbox>
                </apex:column>
 
                <apex:column >
                        <apex:facet name="header">Subject</apex:facet>
                        <apex:outputlink value="/{!Emails.unresolvedeml.id}">
                        <apex:outputField value="{!Emails.unresolvedeml.Subject__c}"/>
                        </apex:outputlink>
                </apex:column>
                <apex:column >
                        <apex:facet name="header">From</apex:facet>
                        <apex:outputField value="{!Emails.unresolvedeml.From__c}"/>
                </apex:column>
                <apex:column >
                        <apex:facet name="header">Assigned To</apex:facet>
                        <apex:outputField value="{!Emails.unresolvedeml.Assigned_To__c}"/>
                </apex:column>
                <apex:column >
                        <apex:facet name="header">Owner</apex:facet>
                        <apex:outputField value="{!Emails.unresolvedeml.owner.name}"/>
                </apex:column>
                 <apex:column >
                        <apex:commandButton value="New Contact" action="{!newContact}" reRender="hiddenBlock">
                                               
                           <apex:param name="unresolvedEmailId"
                            value="{!Emails.unresolvedeml.id}"
                            assignTo="{!unresolvedEmailId}"/>
                        </apex:commandButton>
                        <apex:pageBlock id="hiddenBlock" rendered="false"></apex:pageBlock>               
                  </apex:column>
                  <apex:column >
                        <apex:commandButton value="New Associate" action="{!createAssociate}" reRender="hiddenBlock2" >
                         <apex:param name="unresolvedEmailId"
                            value="{!Emails.unresolvedeml.id}"
                            assignTo="{!unresolvedEmailId}"/>
                        </apex:commandButton>
                       <apex:pageBlock id="hiddenBlock2" rendered="false"></apex:pageBlock>   
               
                                     
                  </apex:column>
                  <apex:column > <apex:selectList value="{!picklistvalue}" size="1" > <Apex:selectOptions value="{!item}" /> <apex:actionSupport event="onchange" action="{!addToSelected}"/> </apex:selectList> </apex:column>
                   
        </apex:pageBlockTable>
         
                  <apex:panelGrid columns="4" style="text-align: center; vertical-align: middle;">
                    <apex:commandLink action="{!first}">First</apex:commandlink>
                    <apex:commandLink action="{!previous}" rendered="{!hasPrevious}">Previous</apex:commandlink>
                    <apex:commandLink action="{!next}" rendered="{!hasNext}">Next</apex:commandlink>
                    <apex:commandLink action="{!last}">Last</apex:commandlink>
                </apex:panelGrid>
               
    </apex:pageBlock>
</apex:form>
<script>
function checkAll(cb)
{
var inputElem = document.getElementsByTagName("input");
for(var i=0; i<inputElem.length; i++)
{
if(inputElem[i].id.indexOf("checkedone")!=-1)
inputElem[i].checked = cb.checked;
}
}    
</script>

</apex:page>

 

bob_buzzardbob_buzzard

Hmm.  You seem to have this selectlist embedded inside a pageblocktable, presumably as you have multiple records to display.  However, every selectlist instance is backed by the same controller property - that means the last to write its information back to the controller will win.  If you have a picklist per record, you'll need to use a wrapper class so that the value can be associated with the record.

SayasoniSayasoni

Am not sure i understand what exactly you mean since i am already using a wrapper class. Let me give you the entire controller as well as a simplified visualforce page.

 

public class UnresolvedEmailsController2 {
    
    public String id;
    public List<selectoption>item{get;set;}

    public string picklistvalue {get;set;}
        
    public UnresolvedEmailsController2() {
                    
    item = new List<selectoption>();
    item.add(new selectoption('None', '-- None --'));
    item.add(new selectoption('SearchToAddToContact','Add to contact'));
    item.add(new selectoption('SearchToAddToAssociate','Add to Associate'));
   }
   public User user = [Select Id,Email,Name,FirstName from User where id = :UserInfo.getUserId()];
   
    
   public ApexPages.StandardSetController setCtrl
    {
   
        get {
            if(setCtrl == null) {
                setCtrl = new ApexPages.StandardSetController(Database.getQueryLocator([Select Id, Subject__c,From__c,Assigned_to__c,owner.name FROM UnresolvedEmail__c  where owner.name = :user.Name ]));
                // sets the number of records in each page set
                setCtrl.setPageSize(20);
                 }
            return setCtrl;
        }
        set;
      
    }
    
  
  //Our collection of the class/wrapper objects cUnresolvedEmails 
    public List<cUnresolvedEmails> unResolvedList {get; set;}

    //This method uses a simple SOQL query to return a List of UnresolvedEmail__c
    public List<cUnresolvedEmails> getUnresolvedEmail() {      
            unResolvedList = new List<cUnresolvedEmails>();
            for(UnresolvedEmail__c c :(List<UnresolvedEmail__c>)setCtrl.getRecords()) {
                // As each UnresolvedEmails is processed we create a new cUnresolvedEmails object and add it to the unResolvedList
                unResolvedList.add(new cUnresolvedEmails(c));
            }
        
        
        return unResolvedList;
    }
    
   
     public PageReference addToSelected() {
     id = ApexPages.currentPage().getParameters().get('id');
     List<UnresolvedEmail__c> selectedEmails = new List<UnresolvedEmail__c>();
    
    
        //We will cycle through our list of cUnresolvedEmails and will check to see if the selected property is set to true, if it is we add the UnresolvedEmail to the selectedEmails list
        for(cUnresolvedEmails cUnr : unResolvedList) {
            if(cUnr.selected == true) {
                selectedEmails.add(cUnr.unreml);
            }
        }
          // Now we have our list of selected contacts to add to
        System.debug('These are the selected Emails...');
        for(UnresolvedEmail__c unreml : selectedEmails) {
            system.debug(unreml);   
          PageReference pageRef=null;
                if (picklistvalue =='None')
                {
               ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Select an option to proceed!'));
                }   
                else 
                {
             pageRef= new PageReference('/apex/'+picklistvalue+'?id=' +unreml.id);
             pageRef.setredirect(true);    
                }
            
             return pageRef;
     } 
            
   
      
             return null;  
   }
      

        
    // indicates whether there are more records after the current page set.
    public Boolean hasNext {
        get {
            return setCtrl.getHasNext();
        }
        set;
    }
 
    // indicates whether there are more records before the current page set.
    public Boolean hasPrevious {
        get {
            return setCtrl.getHasPrevious();
        }
        set;
    }
 
    // returns the page number of the current page set
    public Integer pageNumber {
        get {
            return setCtrl.getPageNumber();
        }
        set;
    }
    
    
    // returns the first page of records
    public void first() {
        setCtrl.first();
    }
 
    // returns the last page of records
    public void last() {
        setCtrl.last();
    }
 
    // returns the previous page of records
    public void previous() {
        setCtrl.previous();
    }
 
    // returns the next page of records
    public void next() {
        setCtrl.next();
    }
    
       
   // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
    public class cUnresolvedEmails {
        public UnresolvedEmail__c unreml {get; set;}
        public Boolean selected {get; set;}

        //This is the contructor method. When we create a new cUnresolvedEmails object we pass an UnresolvedEmail that is set to the unresolvedeml property. We also set the selected value to false
        public cUnresolvedEmails(UnresolvedEmail__c c) {
            unreml = c;
            selected = false;
        }
    }
     
   }

 

<apex:page controller="UnresolvedEmailsController2" >
<style  type="text/css">
  p {color:red }
  </style>
  <p> <b> Please select a record before performing any action!</b> </p>
<apex:form >
  <apex:pageBlock title="Unresolved Emails" mode="edit" >
  <apex:pageMessages /> <!-- this is where the error messages will appear -->
   <apex:pageBlockTable value="{!unresolvedEmail}" var="Emails" >
                <apex:column >
                <apex:facet name="header"> 
                <apex:inputCheckbox >
                <apex:actionSupport event="onclick"  onsubmit="checkAll(this)" rerender="Selected_email"/>
                </apex:inputCheckbox>
                </apex:facet>
                <!-- This is our selected Boolean property in our wrapper class -->
                <apex:inputCheckbox value="{!Emails.selected}" id="checkedone" >
                <apex:actionSupport event="onclick" rerender="Selected_email" />
                </apex:inputCheckbox>
                </apex:column>
 
                <apex:column >
                        <apex:facet name="header">Subject</apex:facet>
                        <apex:outputlink value="/{!Emails.unreml.id}">
                        <apex:outputField value="{!Emails.unreml.Subject__c}"/>
                        </apex:outputlink>
                </apex:column>
                <apex:column >
                        <apex:facet name="header">From</apex:facet>
                        <apex:outputField value="{!Emails.unreml.From__c}"/>
                </apex:column>
                <apex:column >
                        <apex:facet name="header">Assigned To</apex:facet>
                        <apex:outputField value="{!Emails.unreml.Assigned_To__c}"/>
                </apex:column>
                <apex:column >
                        <apex:facet name="header">Owner</apex:facet>
                        <apex:outputField value="{!Emails.unreml.owner.name}"/>
                </apex:column>
                
                  <apex:column > 
                          <apex:selectList value="{!picklistvalue}" size="1" > <Apex:selectOptions value="{!item}" />
                           <apex:actionSupport event="onchange" action="{!addToSelected}"/> </apex:selectList>
                   </apex:column>
                </apex:pageBlockTable>
                   
                    <apex:panelGrid columns="4" style="text-align: center; vertical-align: middle;">
                    <apex:commandLink action="{!first}">First</apex:commandlink>
                    <apex:commandLink action="{!previous}" rendered="{!hasPrevious}">Previous</apex:commandlink>
                    <apex:commandLink action="{!next}" rendered="{!hasNext}">Next</apex:commandlink>
                    <apex:commandLink action="{!last}">Last</apex:commandlink>
                </apex:panelGrid>
               
    </apex:pageBlock>
</apex:form>
<script>
function checkAll(cb)
{
var inputElem = document.getElementsByTagName("input");
for(var i=0; i<inputElem.length; i++)
{
if(inputElem[i].id.indexOf("checkedone")!=-1)
inputElem[i].checked = cb.checked;
}
}    
</script>

</apex:page>
                  

 

 Note: I have also tried this without the wrapper class & it still behaved the same.

bob_buzzardbob_buzzard

While you are using a wrapper class, the picklist section:

 

 <apex:column > 
    <apex:selectList value="{!picklistvalue}" size="1" > <Apex:selectOptions value="{!item}" />
      <apex:actionSupport event="onchange" action="{!addToSelected}"/> 
</apex:selectList> </apex:column>

 

the value is set to {!picklistvalue} - this means that every selectlist on the page is backed by a single controller property.  Thus when you submit the form (e.g. via the actionsupport) each selectlist writes its value to that one property.

 

SayasoniSayasoni

Thanks for your assistance Bob,am not sure how i need to handle this.Could you please help me out on what the best solution for this should look like?

bob_buzzardbob_buzzard

I'd suggest you add another attribute to the wrapper class and use that to back the selectlist.