Reputation: 1570
Using Apache MyFaces JSF 2.0.
XHTML code:
<h:form id="searchUser" prependId="false">
<h:selectManyListbox value="#{listManyBean.listUser}" id="userList" size="10">
<f:selectItems value="#{listManyBean.selListUser}"/>
</h:selectManyListbox>
<h:commandButton id="clickGo" value="#{bundle.btn_login}"
type="submit"
action="#{listManyBean.submitList}"/>
<input type="button" value="Add" onclick="addUserToList();" />
</h:form>
Script to add to the list:
function addUserToList(){
var UserListBox = document.getElementById('UserList');
var UserNum = document.getElementById('UserNumber').value.toUpperCase();
var UserOption = new Option(UserNum,UserNum);
UserListBox.options[UserListBox.options.length] = UserOption;
}
Bean:
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.model.SelectItem;
@ManagedBean
@RequestScoped
public class ListManyBean {
private List<String> listUser;
private List<SelectItem> selListUser;
public List<SelectItem> getSelListUser() {
return selListUser;
}
public List<String> getListUser() {
return listUser;
}
public void setListUser(List<String> listUser) {
this.listUser = listUser;
}
public void submitList() {
System.out.println("User List Value***" + this.listUser);
System.out.println("User ListPan***++"+selListUser);
}
}
I am getting null always, irrespective of adding one or more than one record. Please let me know what is going wrong here.
Upvotes: 1
Views: 574
Reputation: 1109635
You're adding new items using JS instead of using JSF. This way JSF won't know anything about the new items. This information is in no way been submitted to the server side.
Replace your wrong JS approach by a sane JSF approach:
<h:form>
<h:selectManyListbox value="#{bean.selectedUsers}" size="10">
<f:selectItems value="#{bean.availableUsers}" />
</h:selectManyListbox>
<h:commandButton value="submit" action="#{bean.submit}" />
<h:inputText value="#{bean.user}" />
<h:commandButton value="Add" action="#{bean.add}">
<f:ajax execute="@form" render="@form" />
</h:commandButton>
</h:form>
and
@ManagedBean
@ViewScoped
public class Bean {
private List<String> selectedUsers;
private List<String> availableUsers = new ArrayList<String>();
private String user;
public void add() {
availableUsers.add(user);
user = null;
}
public void submit() {
System.out.println("Selected users: " + selectedUsers);
System.out.println("Available users: " + availableUsers);
}
// ...
}
Upvotes: 1