我想在用户输入 inputText 字段时生成 selectOneMenu 内容,并响应组合框选择的更改。
下面的代码在用户键入时更新 selectOneMenu 的内容。(键入的数字和接下来的 9 个数字被添加到组合框中。这只是一个简化的示例代码。)
当页面被加载时,selecOneMenu 的 change 事件被正确触发。但是,在 inputValue 字段中输入后,selecOneMenu 的内容发生了变化,并且当我选择一个项目时不会触发 change 事件。
如果 ComboBean 是会话范围的,则该代码有效,但我想尽可能避免使用此解决方案。
有可能做到这一点吗?
如果请求范围不可能,原因是什么?
PrimeFaces 2.2
Mojarra 2.0.2
GlassFish 3.0.1
浏览器:Chrome、Firefox、IE
组合.xhtml:
<h:head>
<title>Combo box example</title>
</h:head>
<h:body>
<h:form>
<p:panel id="mainPanel">
<h:panelGroup id="formToSubmit" layout="block">
<p:messages id="messages" />
<h:panelGrid columns="2">
<h:outputLabel value="Enter a number" />
<h:inputText id="inputValue" value="#{comboBean.inputValue}">
<p:ajax event="keyup" update="combo"
listener="#{comboBean.onKeyUp}" />
</h:inputText>
<h:outputLabel value="Select a value:" />
<h:selectOneMenu id="combo" value="#{comboBean.selectedValue}">
<f:selectItem itemLabel="Select a value..."
noSelectionOption="true" />
<f:selectItems value="#{comboBean.values}" />
<p:ajax event="change" update="selectedValue"
listener="#{comboBean.valueSelected}" />
</h:selectOneMenu>
<h:outputLabel value="Selected value:" />
<h:inputText id="selectedValue" value="#{comboBean.selectedValue}" />
</h:panelGrid>
</h:panelGroup>
</p:panel>
</h:form>
</h:body>
</html>
ComboBean.java
package x;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
@Named
@RequestScoped
public class ComboBean implements Serializable
{
private static final long serialVersionUID = 1L;
private String inputValue;
private String selectedValue;
private List<String> values;
@PostConstruct
void init()
{
System.out.println("init");
setValues(new LinkedList<String>());
for(int i = 0; i<10 ; i++)
{
getValues().add(""+i);
}
}
public void onKeyUp()
{
System.out.println("onkeyUp " + getInputValue());
setValues(new LinkedList<String>());
if (inputValue != null)
{
try
{
int v = Integer.parseInt(inputValue);
for(int i = 0; i<10 ; i++)
{
getValues().add(""+(v+i));
}
}
catch (NumberFormatException ne)
{
//doesn't matter
}
}
}
public void valueSelected()
{
System.out.println("valueSelected " + getSelectedValue());
}
public void submit()
{
System.out.println("submit " + getInputValue());
}
public void setInputValue(String inputValue)
{
this.inputValue = inputValue;
}
public String getInputValue()
{
return inputValue;
}
public void setSelectedValue(String selectedValue)
{
this.selectedValue = selectedValue;
}
public String getSelectedValue()
{
return selectedValue;
}
public void setValues(List<String> values)
{
this.values = values;
}
public List<String> getValues()
{
return values;
}
}