org.apache.click.control
Class Select

java.lang.Object
  extended by org.apache.click.control.AbstractControl
      extended by org.apache.click.control.Field
          extended by org.apache.click.control.Select
All Implemented Interfaces:
Serializable, Control, Stateful

public class Select
extends Field

Provides a Select control:   <select></select>.

Select
The Control listener will be invoked if the Select is valid and an item(s) is selected by the user.

Select Examples

Single Item Select

A single item Select, will only allow users to select one item from the list. By default the Select multiple item property is false.

If a Select is required, an item after the first in the list must be selected for the Field to be valid. This forces the user to make an active selection. An example of a single item Select is provided below along with the rendered HTML.

 public class GenderPage extends Page {

     public Form form = new Form();

     private Select genderSelect = new Select("Gender");

     public GenderPage() {
         genderSelect.setRequired(true);
         genderSelect.add(new Option("U", "");
         genderSelect.add(new Option("M", "Male"));
         genderSelect.add(new Option("F", "Female"));
         form.add(genderSelect);

         form.add(new Submit("ok", "  OK  "));
     }

     public void onPost() {
         if (form.isValid()) {
             String gender = genderSelect.getValue();
             ..
         }
     }
 } 
Rendered HTML:
*
 
Note how Option items are added to the Select. In this example the "U" option will not be a valid selection, as it is the first item in the option list.

Multiple Item Select

A multiple item Select, will allow users to select multiple items from the list. By default the Select multiple item property is false, and must be enabled for multiple item selects.

If multiple item Select is required, the user must select an item(s) in the list for the Field to be valid. A valid selection can include any item including the first item.

An example of a single item Select is provided below along with the rendered HTML.

 public class LocationPage extends Page {

     public Form form = new Form();

     private Select locationSelect = new Select("location");

     public LocationPage() {
         locationSelect.setMutliple(true);
         locationSelect.setRequired(true);
         locationSelect.setSize(7);
         locationSelect.add("QLD");
         locationSelect.add("NSW");
         locationSelect.add("NT");
         locationSelect.add("SA");
         locationSelect.add("TAS");
         locationSelect.add("VIC");
         locationSelect.add("WA");
         form.add(locationSelect);

         form.add(new Submit("ok", "  OK  "));
     }

     public void onPost() {
         if (form.isValid()) {
             String location = locationSelect.getValue();
             ..
         }
     }
 } 
Rendered HTML:
*
 
Note in this example the add(String) method is used to add an Option item to the Select.

Required Behaviour

When a Select control's required property is set to true, then the user has to select a value other than the first value in the option list. The first value represents a non-selection by the user. In the example below an Empty Option is set as the first value in the option list.
 public MyPage extends Page {
     ..

     private Select mySelect;

     public MyPage() {
         mySelect = new Select("mySelect");
         mySelect.setRequired(true);

         ..
     }

     public void onInit() {
         mySelect.add(Option.EMPTY_OPTION);
         List<Customer> customerList = customerDao.getCustomerList();
         mySelect.addAll(customerList, "id", "name");
     }

     ..
 } 
Unless you use a DataProvider, remember to always populate the Select option list before it is processed. Do not populate the option list in a Page's onRender() method.

Readonly Behaviour

Note the <select> HTML element does not support the "readonly" attribute. To provide readonly style behaviour, the Select control will render the "disabled" attribute when it is readonly to give the appearance of a readonly field, and will render a hidden field of the same name so that its value will be submitted with the form.

DataProvider

A common issue new Click users face is which page event (onInit or onRender) to populate the Select optionList in. To alleviate this problem you can set a dataProvider which allows the Select to fetch data when needed. This is particularly useful if retrieveing Select data is expensive e.g. loading from a database.

Below is a simple example:

 public class GenderPage extends Page {

     public Form form = new Form();

     private Select genderSelect = new Select("Gender");

     public GenderPage() {

         // Set the Select default "non-selection" option
         genderSelect.setDefaultOption(new Option("U", "");

         // Set a DataProvider which "getData" method will be called to populate the
         // optionList. The "getData" method is only called when the optionList
         // data is needed
         genderSelect.setDataProvider(new DataProvider() {
             public List getData() {
                 List options = new ArrayList();
                 options.add(new Option("M", "Male"));
                 options.add(new Option("F", "Female"));
                 return options;
             }
         });

         form.add(genderSelect);

         form.add(new Submit("ok", "  OK  "));
     }

     public void onPost() {
         if (form.isValid()) {
             String gender = genderSelect.getValue();
             ..
         }
     }
 } 

Specify the default selected value

If you need to set the selected value to something other than the first option, set the Select value to the option value you want to select:
 public MyPage extends Page {
     private Select mySelect;

     public MyPage() {
         mySelect = new Select("mySelect");
         mySelect.add("YES");
         mySelect.add("NO");

         // If you want NO to be selected by default, set the value to "NO"
         mySelect.setValue("NO");
     }
 } 
See also the W3C HTML reference: SELECT

See Also:
Option, OptionGroup, Serialized Form

Field Summary
protected  DataProvider dataProvider
          The select data provider.
protected  Option defaultOption
          The default option will be the first option added to the Select.
protected  boolean multiple
          The multiple options selectable flag.
protected  List optionList
          The Select Option/OptionGroup list.
protected  List<String> selectedValues
          The multiple selected values.
protected  int size
          The Select display size in rows.
protected static String VALIDATE_SELECT_FUNCTION
          The field validation JavaScript function template.
 
Fields inherited from class org.apache.click.control.Field
disabled, error, focus, form, help, label, labelStyle, labelStyleClass, parentStyleClassHint, parentStyleHint, readonly, required, tabindex, title, trim, validate, value
 
Fields inherited from class org.apache.click.control.AbstractControl
actionListener, attributes, behaviors, headElements, listener, listenerMethod, messages, name, parent, styles
 
Fields inherited from interface org.apache.click.Control
CONTROL_MESSAGES
 
Constructor Summary
Select()
          Create a Select field with no name defined.
Select(String name)
          Create a Select field with the given name.
Select(String name, boolean required)
          Create a Select field with the given name and required status.
Select(String name, String label)
          Create a Select field with the given name and label.
Select(String name, String label, boolean required)
          Create a Select field with the given name, label and required status.
 
Method Summary
 void add(Object option)
          Add the given Option/OptionGroup/String/Number/Boolean to the Select.
 void add(Option option)
          Add the given Option to the Select.
 void add(OptionGroup optionGroup)
          Add the given OptionGroup to the Select.
 void add(String value)
          Add the given option value to the Select.
 void addAll(Collection<?> options)
          Add the given Option/OptionGroup/String/Number/Boolean collection to the Select.
 void addAll(Collection objects, String optionValueProperty, String optionLabelProperty)
          Add the given collection of objects to the Select, creating new Option instances based on the object properties specified by optionValueProperty and optionLabelProperty.
 void addAll(Map options)
          Add the given Map of option values and labels to the Select.
 void addAll(String[] options)
          Add the given array of string options to the Select option list.
 void bindRequestValue()
          Bind the request submission, setting the Field.value or selectedValues property if defined in the request.
 int getControlSizeEst()
          Return the estimated rendered control size in characters.
 DataProvider getDataProvider()
          Return the select option list DataProvider.
 Option getDefaultOption()
          Return the Select default option or null if no default option is set.
protected  String getDefaultOptionValue()
          Return the Select defaultOption value, or null if no defaultOption is set.
 List getMultipleValues()
          Deprecated. use getSelectedValues() instead, this method will be removed in subsequent releases
 List getOptionList()
          Return the Option list.
 List getSelectedValues()
          Return the list of selected values.
 int getSize()
          Return the number of Select display rows.
 Object getState()
          Return the Select state.
 String getTag()
          Return the select's html tag: select.
 String getValidationJavaScript()
          Return the Select JavaScript client side validation function.
 boolean isMultiple()
          Return true if multiple options can be selected.
 void onRender()
          This method invokes getOptionList() to ensure exceptions thrown while retrieving options will be handled by the error page.
 void render(HtmlStringBuffer buffer)
          Render the HTML representation of the Select.
 void setDataProvider(DataProvider dataProvider)
          Set the select option list DataProvider.
 void setDefaultOption(Option option)
          Set the Select default option.
protected  void setInitialValue()
          Set the initial select option value.
 void setMultiple(boolean value)
          Set the multiple options can be selected flag.
 void setMultipleValues(List<String> multipleValues)
          Deprecated. use getSelectedValues() instead, this method will be removed in subsequent releases
 void setOptionList(List options)
          Set the Option list.
 void setSelectedValues(List<String> multipleValues)
          Set the list of selected values.
 void setSize(int rows)
          Set the number of the Select display rows.
 void setState(Object state)
          Set the Select state.
 void validate()
          Validate the Select request submission.
 
Methods inherited from class org.apache.click.control.Field
getError, getErrorLabel, getFocus, getFocusJavaScript, getForm, getHelp, getId, getLabel, getLabelStyle, getLabelStyleClass, getParentStyleClassHint, getParentStyleHint, getRequestValue, getTabIndex, getTextAlign, getTitle, getValidate, getValue, getValueObject, getWidth, isDisabled, isHidden, isReadonly, isRequired, isTrim, isValid, onProcess, removeState, renderTagBegin, restoreState, saveState, setDisabled, setError, setErrorMessage, setErrorMessage, setFocus, setForm, setHelp, setLabel, setLabelStyle, setLabelStyleClass, setListener, setParent, setParentStyleClassHint, setParentStyleHint, setReadonly, setRequired, setTabIndex, setTextAlign, setTitle, setTrim, setValidate, setValue, setValueObject, setWidth
 
Methods inherited from class org.apache.click.control.AbstractControl
addBehavior, addStyleClass, appendAttributes, dispatchActionEvent, getActionListener, getAttribute, getAttributes, getBehaviors, getContext, getHeadElements, getHtmlImports, getMessage, getMessage, getMessages, getName, getPage, getParent, getStyle, getStyles, hasAttribute, hasAttributes, hasBehaviors, hasStyles, isAjaxTarget, onDeploy, onDestroy, onInit, removeBehavior, removeStyleClass, renderTagEnd, setActionListener, setAttribute, setId, setName, setStyle, toString
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

VALIDATE_SELECT_FUNCTION

protected static final String VALIDATE_SELECT_FUNCTION
The field validation JavaScript function template. The function template arguments are:

See Also:
Constant Field Values

multiple

protected boolean multiple
The multiple options selectable flag. The default value is false.


optionList

protected List optionList
The Select Option/OptionGroup list.


size

protected int size
The Select display size in rows. The default size is one.


selectedValues

protected List<String> selectedValues
The multiple selected values. This list will only be populated if multiple is true.


dataProvider

protected DataProvider dataProvider
The select data provider.


defaultOption

protected Option defaultOption
The default option will be the first option added to the Select. This property is often used when populating the Select from a setDataProvider(org.apache.click.dataprovider.DataProvider), where the DataProvider does not return a sensible default option e.g. an empty ("") option.

Constructor Detail

Select

public Select(String name)
Create a Select field with the given name.

Parameters:
name - the name of the field

Select

public Select(String name,
              String label)
Create a Select field with the given name and label.

Parameters:
name - the name of the field
label - the label of the field

Select

public Select(String name,
              boolean required)
Create a Select field with the given name and required status.

Parameters:
name - the name of the field
required - the field required status

Select

public Select(String name,
              String label,
              boolean required)
Create a Select field with the given name, label and required status.

Parameters:
name - the name of the field
label - the label of the field
required - the field required status

Select

public Select()
Create a Select field with no name defined.

Please note the control's name must be defined before it is valid.

Method Detail

getTag

public String getTag()
Return the select's html tag: select.

Overrides:
getTag in class AbstractControl
Returns:
this controls html tag
See Also:
AbstractControl.getTag()

add

public void add(Option option)
Add the given Option to the Select.

Parameters:
option - the Option value to add
Throws:
IllegalArgumentException - if option is null

add

public void add(OptionGroup optionGroup)
Add the given OptionGroup to the Select.

Parameters:
optionGroup - the OptionGroup value to add
Throws:
IllegalArgumentException - if optionGroup is null

add

public void add(String value)
Add the given option value to the Select. This convenience method will create a new Option with the given value and add it to the Select. The new Option display label will be the same as its value.

Parameters:
value - the option value to add
Throws:
IllegalArgumentException - if the value is null

add

public void add(Object option)
Add the given Option/OptionGroup/String/Number/Boolean to the Select.

Parameters:
option - one of either Option/OptionGroup/String/Number/Boolean to add
Throws:
IllegalArgumentException - if option is null, or the option is an unsupported class

addAll

public void addAll(Collection<?> options)
Add the given Option/OptionGroup/String/Number/Boolean collection to the Select.

Parameters:
options - the collection of Option/OptionGroup/String/Number/Boolean objects to add
Throws:
IllegalArgumentException - if options is null, or the collection contains an unsupported class

addAll

public void addAll(Map options)
Add the given Map of option values and labels to the Select. The Map entry key will be used as the option value and the Map entry value will be used as the option label.

It is recommended that LinkedHashMap is used as the Map parameter to maintain the order of the option vales.

Parameters:
options - the Map of option values and labels to add
Throws:
IllegalArgumentException - if options is null

addAll

public void addAll(String[] options)
Add the given array of string options to the Select option list.

The options array string value will be used for the Option.value and Option.label.

Parameters:
options - the array of option values to add
Throws:
IllegalArgumentException - if options is null

addAll

public void addAll(Collection objects,
                   String optionValueProperty,
                   String optionLabelProperty)
Add the given collection of objects to the Select, creating new Option instances based on the object properties specified by optionValueProperty and optionLabelProperty. If the optionLabelProperty is null, the optionValueProperty will be used as both the value and label of the options.

The collection objects can either be POJOs (plain old java objects) or Map instances.

Example usage:

 Select select = new Select("type", "Type:");
 select.addAll(getCustomerService().getCustomerTypes(), "id", "name");
 form.add(select); 
This method will iterate over all customerTypes and for each customerType create a new Option, setting the option value to the customerType "id", and the option label to the customerType "name".

Parameters:
objects - the collection of objects to render as options
optionValueProperty - the name of the object property to render as the Option value
optionLabelProperty - the name of the object property to render as the Option label
Throws:
IllegalArgumentException - if objects or optionValueProperty parameter is null

getDataProvider

public DataProvider getDataProvider()
Return the select option list DataProvider.

Returns:
the select option list DataProvider

setDataProvider

public void setDataProvider(DataProvider dataProvider)
Set the select option list DataProvider. The dataProvider can return any mixture of Option and OptionGroup values.

Example usage:

 Select select = new Select("name", "Name");

 // Set the Select default "non-selection" option
 select.setDefaultOption(new Option("U", ""));

 select.setDataProvider(new DataProvider() {
     public List getData() {
         List options = new ArrayList();
         options.add(new Option("M", "Male"));
         options.add(new Option("F", "Female"));
         return options;
     }
 }); 

Parameters:
dataProvider - the select option list DataProvider

getSize

public int getSize()
Return the number of Select display rows.

Returns:
the number of Select display rows

setSize

public void setSize(int rows)
Set the number of the Select display rows.

Parameters:
rows - the Select display size in rows.

isMultiple

public boolean isMultiple()
Return true if multiple options can be selected.

Returns:
true if multiple options can be selected

setMultiple

public void setMultiple(boolean value)
Set the multiple options can be selected flag.

Parameters:
value - the multiple options can be selected flag

getMultipleValues

public List getMultipleValues()
Deprecated. use getSelectedValues() instead, this method will be removed in subsequent releases

Return the list of selected values.

Returns:
the list of selected values

getSelectedValues

public List getSelectedValues()
Return the list of selected values.

Returns:
the list of selected values

setMultipleValues

public void setMultipleValues(List<String> multipleValues)
Deprecated. use getSelectedValues() instead, this method will be removed in subsequent releases

Set the list of selected values.

Parameters:
multipleValues - the list of selected values

setSelectedValues

public void setSelectedValues(List<String> multipleValues)
Set the list of selected values.

Parameters:
multipleValues - the list of selected values

setDefaultOption

public void setDefaultOption(Option option)
Set the Select default option. The default option will be the first option added to the Select optionList.

Please note: this property is used in conjunction with the Select dataProvider, where the DataProvider does not return a sensible default, non-selecting option. For example if the DataProvider returns a list of Authors from the database, the list won't include a default empty ("") option to choose from. By setting the defaultOption property, the Select will add this Option as the first option of the Select optionList.

In addition, if the Select is required, the defaultOption is used to check whether the Select is valid or not. In other words, if the user's selected value equals the defaultOption value, the Select won't be valid since no selection was made by the user.

Example usage:

 public void onInit() {
     authorSelect.setDefaultOption(Option.EMPTY_OPTION);

     authorSelect.setDataProvider(new DataProvider() {
         public List getData() {
             List options = new ArrayList();
             List authors = getAuthorDao().getAuthors();
             for (Author author : authors) {
                 options.add(new Option(author.getId(), author.getName()));
             }
             return options;
         }
     });
     form.add(authorSelect);
 } 

Parameters:
option - the Select default option

getDefaultOption

public Option getDefaultOption()
Return the Select default option or null if no default option is set.

Returns:
the Select default option or null if no default option is set
See Also:
setDefaultOption(org.apache.click.control.Option)

getOptionList

public List getOptionList()
Return the Option list.

Returns:
the Option list

setOptionList

public void setOptionList(List options)
Set the Option list.

Parameters:
options - the Option list

getValidationJavaScript

public String getValidationJavaScript()
Return the Select JavaScript client side validation function.

Overrides:
getValidationJavaScript in class Field
Returns:
the field JavaScript client side validation function

bindRequestValue

public void bindRequestValue()
Bind the request submission, setting the Field.value or selectedValues property if defined in the request.

Overrides:
bindRequestValue in class Field

getState

public Object getState()
Return the Select state. The following state is returned, depending on whether isMultiple() is true or false:

Specified by:
getState in interface Stateful
Overrides:
getState in class Field
Returns:
the Select state

setState

public void setState(Object state)
Set the Select state.

Specified by:
setState in interface Stateful
Overrides:
setState in class Field
Parameters:
state - the Select state to set

onRender

public void onRender()
This method invokes getOptionList() to ensure exceptions thrown while retrieving options will be handled by the error page.

Specified by:
onRender in interface Control
Overrides:
onRender in class AbstractControl
See Also:
Control.onRender()

getControlSizeEst

public int getControlSizeEst()
Description copied from class: AbstractControl
Return the estimated rendered control size in characters.

Overrides:
getControlSizeEst in class AbstractControl
Returns:
the estimated rendered control size in characters
See Also:
AbstractControl.getControlSizeEst()

render

public void render(HtmlStringBuffer buffer)
Render the HTML representation of the Select.

Specified by:
render in interface Control
Overrides:
render in class AbstractControl
Parameters:
buffer - the specified buffer to render the control's output to
See Also:
AbstractControl.toString()

validate

public void validate()
Validate the Select request submission.

If a Select is Field.required then the user must select a value other than the first value is the list, otherwise the Select will have a validation error. If the Select is not required then no validation errors will occur.

A field error message is displayed if a validation error occurs. These messages are defined in the resource bundle:

/click-control.properties

Error message bundle key names include:

  • select-error

Overrides:
validate in class Field

getDefaultOptionValue

protected String getDefaultOptionValue()
Return the Select defaultOption value, or null if no defaultOption is set.

Returns:
the Select defaultOption value, or null if no defaultOption is set
See Also:
getDefaultOption(), setDefaultOption(org.apache.click.control.Option)

setInitialValue

protected void setInitialValue()
Set the initial select option value.