+ Start a Discussion
MayTheForceBeWithYouMayTheForceBeWithYou 

Populating a selectList using Javascript with required Name field blank

I have a Visualforce page that emulates the functionality of the standard Salesforce Public Group edit page (Setup>>Manage Users>>Public Groups>>Edit) and it's (finally!) fully functional; however, there is one small edit I have been asked to make that I'm having difficulty with.  My reading and experience have shown that all required fields (at top of page) must be filled in order for the selectList functionality below to work; unfortunately I have been given the strict requirement of leaving the Name field blank and when I do this, as expected, the Add/Remove buttons do not work properly.  I've even tried leaving a blank space as the default value but this does not help (Currently the default has been left as '|'); it seems I must have text in the inputField textbox for the page to function properly. Anyone know how to overcome this issue? Thanks!

 

VFPage:

<apex:page standardController="Janela_de_Acesso__c" extensions="JDABP" sidebar="false">
<apex:sectionHeader title="Janela de Acesso"/>
<apex:form >
<div align="center">
<apex:messages styleClass="errorMsg"/>
<apex:commandButton action="{!SaveRecord}" value="Salvar"/>
<apex:commandButton action="{!SaveAndNew}" value="Salvar & Nova"/>
<apex:commandButton action="{!Cancel}" value="Cancelar"/>
</div>
<apex:pageBlock >
<apex:pageBlockSection title="Informações" columns="2">
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Name}" />
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Data_Inicial__c}"/>
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Status__c}"/>
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Data_Final__c}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Membros da Janela de Acesso" columns="1">
<apex:panelGrid columns="2" cellpadding="5px">
<apex:pageBlockSectionItem labelStyle="vertical-align: middle" >
<apex:outputLabel value="Pesquisa:" for="SearchList"/>
<apex:selectList title="Pesquisa" size="1" id="pesquisa" onchange="searchServer(this.options[this.selectedIndex].text);">
<apex:selectOptions value="{!items}"/>
<apex:actionFunction immediate="true" name="searchServer" action="{!runSearch}" reRender="Available,Over">
<apex:param assignTo="{!sObjectDesc}" name="pesq" value="" />
</apex:actionFunction>
</apex:selectList>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem labelStyle="vertical-align: middle">
<apex:outputLabel value="for:" for="SearchBox"/>
<apex:inputText id="SearchBox"  onkeyup="searchServer2(this.value);">
<apex:actionFunction immediate="true" name="searchServer2" action="{!runSearch}" reRender="Available,Over">
<apex:param assignTo="{!searchText}" name="searchB" value="" />
</apex:actionFunction>
</apex:inputText>
</apex:pageBlockSectionItem>
</apex:panelGrid>
<apex:outputPanel id="Over">
<apex:outputText rendered="{!overMax}" value="A consulta retornou mais de 100 registros. Somente as 100 primeiras linhas são exibidas. Por favor, refine os critérios da busca." style="text-align:center;color:red"/>
</apex:outputPanel>
<apex:panelGrid columns="3" style="text-align: center; vertical-align: middle;">
<apex:panelGroup style="padding-right:3px;align:center">
<apex:outputLabel value="Membros Disponíveis" style="font-weight:bold"/>
<br/>
<apex:selectList title="Membros Disponíveis" multiselect="true" size="14" required="false" id="Available" value="{!selected}">
<apex:selectOptions value="{!searchResults}"/>
</apex:selectList>
</apex:panelGroup>
<apex:panelGroup >
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<apex:outputLabel value="Adicionar"/>
<br/>
<apex:commandButton action="{!DoSelect}" value=">>" rerender="Available,Selected"/>
<br/>
<apex:commandButton action="{!DoUnselect}" value="<<" rerender="Available,Selected"/>
<br/>
<apex:outputLabel value="Excluir"/>
</apex:panelGroup>
<apex:panelGroup style="align:center;">
<apex:outputLabel value="Membros Selecionados" style="font-weight:bold"/>
<br/>
<apex:selectList title="Membros Selecionados" multiselect="true" size="14" required="false" id="Selected" value="{!unselected}">
<apex:selectOptions value="{!selectResults}"/>
</apex:selectList>
</apex:panelGroup>
</apex:panelGrid>
</apex:pageBlockSection>
</apex:pageBlock>
<div align="center">
<apex:commandButton action="{!SaveRecord}" value="Salvar"/>
<apex:commandButton action="{!SaveAndNew}" value="Salvar & Nova"/>
<apex:commandButton action="{!Cancel}" value="Cancelar"/>
</div>
</apex:form>
</apex:page>

 

Controller:

public class JDABP {    
    
    // the soql without the order and limit
    private String soql {get;set;}
    // the collection of contacts to display
    public List<sObject> results {get;set;}
    public Boolean overMax=false;
    public String searchObject;
    public Janela_de_Acesso__c j;
    public List<SelectOption> searchResult = new List<SelectOption>();
    public List<SelectOption> selectResult = new List<SelectOption>();
    public String searchText {get;set;}
    public String sObjectDesc {get;set;}
    public List<String> selected {get; set;}
    public List<String> unselected {get; set;}
    
    //Constructor to apply fields
    public JDABP(ApexPages.StandardController controller) {
        j = (Janela_de_Acesso__c) controller.getRecord();
        j.Name='|';
        j.Status__c='Ativo';
        j.Data_Inicial__c=System.now();
        j.Data_Final__c=System.today()+30;        
        j.RecordTypeId = Label.Janela_de_Acesso_BP_RecordType;
        j.sObjectIds__c='';
        j.sObjectDesc__c='';
        searchText = '';
        sObjectDesc = 'Business Plans';
        searchObject = 'Business_Plan__c';
        soql = 'select Id, Name, Business_Plan_Conta__r.Name from ' + searchObject + ' order by Name limit 100';
        runQuery();

    }
    
    public List<SelectOption> getItems() {
        List<SelectOption> options = new List<SelectOption>();
        options.add(new SelectOption('Business Plans','Business Plans'));
        options.add(new SelectOption('Perfis','Perfis'));
        options.add(new SelectOption('Usuários','Usuários'));
        return options;
    }     
    
    public List<SelectOption> getSearchResults() {
        return searchResult;
    }
    
    public List<SelectOption> getSelectResults() {
        return selectResult;
    }
    
    // runs the actual query
    public void runQuery() {    
        try {
          results = Database.query(soql);
          if (results.size()==100){
            overMax=true;
          }    
          else {
            overMax=false;
          }        
          searchResult.clear(); 
          for (sObject r : results){
              If (sObjectDesc.contains('Business Plans')){
                  Business_Plan__c BPr = (Business_Plan__c) r;
                  searchResult.add(new SelectOption(BPr.Id,BPr.Name+' :: '+BPr.business_plan_conta__r.Name));                    
                  for (SelectOption s: selectResult) {
                      for (Integer i=0; i<searchResult.size(); i++){
                          if (searchResult[i].getValue()==s.getValue()){
                              searchResult.remove(i);
                              i--;
                          }
                      }
                  }
              }
              Else If (sObjectDesc.contains('Perfis')){
                  Profile Pr = (Profile) r;
                  searchResult.add(new SelectOption(Pr.Id,Pr.Name));
                  for (SelectOption s: selectResult) {
                      for (Integer i=0; i<searchResult.size(); i++){
                          if (searchResult[i].getValue()==s.getValue()){
                              searchResult.remove(i);
                              i--;
                          }
                      }
                  }
              }
              Else If (sObjectDesc.contains('Usuários')){
                  User Ur = (User) r;
                  searchResult.add(new SelectOption(Ur.Id,Ur.Name));
                  for (SelectOption s: selectResult) {
                      for (Integer i=0; i<searchResult.size(); i++){
                          if (searchResult[i].getValue()==s.getValue()){
                              searchResult.remove(i);
                              i--;
                          }
                      }
                  }
              }        
          }           
        } catch (Exception e) {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Ocorreu um erro ao efetuar a busca, por favor, tente novamente'));
          }
 
  }

  // runs the search with parameters passed via Javascript
  public PageReference runSearch() {
    If (sObjectDesc.contains('Business Plans')){
        searchObject='Business_Plan__c';
    }
    Else If (sObjectDesc.contains('Perfis')){
        searchObject='Profile';
    }
    Else If (sObjectDesc.contains('Usuários')){
        searchObject='User';
    }
    soql = 'select Id, Name from ' + searchObject;
    If (sObjectDesc.contains('Business Plans')){
        soql = soql.replace('select Id, Name from','select Id, Name, Business_Plan_Conta__r.Name from');
        soql += ' where Name LIKE \''+'%'+String.escapeSingleQuotes(searchText)+'%\' or business_plan_conta__r.name LIKE \''+'%'+String.escapeSingleQuotes(searchText)+'%\'';
    }
    Else {
        if (!searchText.equals('')){
          soql += ' where Name LIKE \''+'%'+String.escapeSingleQuotes(searchText)+'%\'';   
        }
    }
    soql += ' order by Name limit 100';  
    // run the query again
    runQuery(); 
    return null;
  }
  
  public PageReference doSelect() {
        for (String s: selected) {
            for (Integer i=0; i<searchResult.size(); i++){
                if (searchResult[i].getValue()==s){
                    selectResult.add(new SelectOption(s,searchResult[i].getLabel()));
                    searchResult.remove(i);
                    i--;
                }
            }
        }
        return null;
    }

    public PageReference doUnSelect() {
        for (String s: unselected) {
            for (Integer i=0; i<selectResult.size(); i++){
                if (selectResult[i].getValue()==s){
                    searchResult.add(new SelectOption(s,selectResult[i].getLabel()));
                    selectResult.remove(i);
                    i--;
                }
            }
        }
        return null;
    }
        
    //Override Save & New Functionality
    public PageReference SaveAndNew() {
        try{
            for (selectOption s : selectResult){
                j.sObjectIds__c += s.getValue()+';';
                if (s.getValue().startswith(Label.BP_Id)){
                    j.sObjectDesc__c += 'Business Plan :: '+s.getLabel()+';';
                }
                else if (s.getValue().startswith(Label.Perfil_Id)){
                    j.sObjectDesc__c += 'Perfil :: '+s.getLabel()+';';
                }
                else if (s.getValue().startswith(Label.User_Id)){
                    j.sObjectDesc__c += 'Usuário :: '+s.getLabel()+';';
                }
            }
            insert j;
        } catch (DMLException e) {return null;}
        PageReference pr = new PageReference('/apex/JDABP');
        pr.setRedirect(true);
        return pr;
    }
    
    public Boolean getOverMax(){
        return overMax;
    }
    
    //Override Save Functionality
    public PageReference SaveRecord() {
        try{
            for (selectOption s : selectResult){
                j.sObjectIds__c += s.getValue()+';';
                if (s.getValue().startswith(Label.BP_Id)){
                    j.sObjectDesc__c += 'Business Plan :: '+s.getLabel()+';';
                }
                else if (s.getValue().startswith(Label.Perfil_Id)){
                    j.sObjectDesc__c += 'Perfil :: '+s.getLabel()+';';
                }
                else if (s.getValue().startswith(Label.User_Id)){
                    j.sObjectDesc__c += 'Usuário :: '+s.getLabel()+';';
                }
            }
            insert j;
        } catch (DMLException e) {return null;}
        PageReference pr = new PageReference('/'+j.Id);
        pr.setRedirect(true);
        return pr;
    }

}

 

 

Best Answer chosen by Admin (Salesforce Developers) 
bob_buzzardbob_buzzard

These are required fields because you have mandated that via the required attribute:

 

<apex:inputField required="true" value="{!Janela_de_Acesso__c.Name}" />
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Data_Inicial__c}"/>
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Status__c}"/>
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Data_Final__c}"/>

However, as you are using custom objects, it is permissable to have the name not required, according to the visualforce docs on the required attribute:

 

--- snip ---

 

A Boolean value that specifies whether this inputField is a required field. If set to true, the user must specify a value for this field. If not selected, this value defaults to false.Note that if this input field displays a custom object name its value can be set to nil and will not be required unless you set this attribute to true. The same does not apply tostandard object names, which are always required regardless of this attribute.

 

--- snip ---

 

 

All Answers

bob_buzzardbob_buzzard

These are required fields because you have mandated that via the required attribute:

 

<apex:inputField required="true" value="{!Janela_de_Acesso__c.Name}" />
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Data_Inicial__c}"/>
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Status__c}"/>
<apex:inputField required="true" value="{!Janela_de_Acesso__c.Data_Final__c}"/>

However, as you are using custom objects, it is permissable to have the name not required, according to the visualforce docs on the required attribute:

 

--- snip ---

 

A Boolean value that specifies whether this inputField is a required field. If set to true, the user must specify a value for this field. If not selected, this value defaults to false.Note that if this input field displays a custom object name its value can be set to nil and will not be required unless you set this attribute to true. The same does not apply tostandard object names, which are always required regardless of this attribute.

 

--- snip ---

 

 

This was selected as the best answer
MayTheForceBeWithYouMayTheForceBeWithYou

What an embarrassing oversight on my part, I had just assumed that it was required as it is for standard objects! That's why it's good to have a second set of eyes double-check your work I suppose, thanks so much Bob!