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 ApplicationThe 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);
}
}
}
}
0 comments:
Post a Comment