A Programmatic SelectOneChoice Example

This sample application demonstrates how to add/delete selectitems in a selectOneChoice component programmatically. The JDeveloper 10.1.3.2 workspace can be downloaded from here. The sample application does not need a database connection to run.

Sample Application

The application displays a list box and an input field. The user can add new items to the list box by typing a new value to the input field and clicking the “Add Item to List” button. Pressing the “Remove Selected Item From List” button will remove the current selected value from the list box.

Below is the source code for the JSP Page and the managed bean used to provide the functionality.

<h:panelGrid columns="2" cellpadding="10" cellspacing="15">
<af:inputText label="New Item Name"
binding="#{MyTestBean.newItemNameComponent}"/>

<af:selectOneChoice label="List"
binding="#{MyTestBean.myTestListComponent}">
<f:selectItems value="#{MyTestBean.listOfItems}"/>
</af:selectOneChoice>

<af:commandButton text="Add Item To List"
actionListener="#{MyTestBean.addNewItemToList}"/>

<af:commandButton text="Remove Selected Item From List"
actionListener="#{MyTestBean.removeItemFromList}"
disabled="#{empty MyTestBean.listOfItems}"/>
</h:panelGrid>
public void addNewItemToList(ActionEvent actionEvent)
{
String value = (String)newItemNameComponent.getValue();
if(value != null && !value.equals(""))
{
SelectItem si = new SelectItem();
si.setLabel(value);
si.setValue(value);
listOfItems.add(si);
myTestListComponent.setValue(value);
newItemNameComponent.setValue("");
}
}

public void removeItemFromList(ActionEvent actionEvent)
{
String removedValue = (String)myTestListComponent.getValue();
if(removedValue != null && !removedValue.equals(""))
{
for(int i = 0; i < listOfItems.size(); i++)
{
SelectItem si = (SelectItem)listOfItems.get(i);
if(si.getValue().equals(removedValue))
{
myTestListComponent.setValue(null);
listOfItems.remove(i);
}
}
}
}

Comments

Anonymous said…
Hello !!

Very Thanks for this example it is very useful and simple, I learn how to get a item of a selecOneChoice component and how to set value to this.

I want to say you that "String" is the class of the getValue method of SelectOneChoice´s component.

Very Thanks from Coahuila, México !!
Anonymous said…
Thanks for the blog loaded with so many information. Stopping by your blog helped me to get what I was looking for.

Popular posts from this blog

PostgreSQL for Oracle Developers and DBA's