怎麼這樣
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewScoped
public class AddressBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2439322307625952605L;
private List<String> countries;
private List<String> states;
private Address address;
private boolean disableState;
private Map<String,List<String>> map = new HashMap<String,List<String>>();
@PostConstruct
public void init(){
address= new Address();
countries = new ArrayList<String>();
states = new ArrayList<String>();
countries.add("Australia");
countries.add("Other");
String[] s1 = {"state 1","state 2"};
String[] s2 = {"state 3","state 4"};
map.put("Australia", Arrays.asList(s1));
map.put("Other", Arrays.asList(s2));
this.disableState = "Australia".equals(countries.get(0));
}
public void updateState(){
this.states = map.get(this.address.getCountry());
this.disableState = "Australia".equals(this.address.getCountry());
}
public List<String> getCountries() {
return countries;
}
public void setCountries(List<String> countries) {
this.countries = countries;
}
public List<String> getStates() {
return states;
}
public void setStates(List<String> states) {
this.states = states;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public boolean isDisableState() {
return disableState;
}
public void setDisableState(boolean disableState) {
this.disableState = disableState;
}
}
和
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head></h:head>
<h:body>
<h:form>
<h:outputLabel value="Country"
for="addcountry" />
<p:selectOneMenu id="addcountry" value="#{addressBean.address.country}">
<f:selectItems value="#{addressBean.getCountries()}" />
<p:ajax listener="#{addressBean.updateState}" update="addstate"/>
</p:selectOneMenu>
<h:outputLabel value="State" for="addstate" />
<p:selectOneMenu id="addstate" value="#{addressBean.address.state}" disabled="#{addressBean.disableState}">
<f:selectItem itemLabel="Select State" itemValue="" />
<f:selectItems value="#{addressBean.getStates()}" />
</p:selectOneMenu>
</h:form>
</h:body>
</html>
好方法,但對於我的代碼是我如何不幸結構不完全正確。 實際的問題似乎是,因爲addressBean.adress.country最初是一個空字符串,直到它被分配了一個隨後被更改的值,事件纔會被觸發,這意味着事件不會被觸發,第二選擇。 – Ectomorph
更新:我從第二個seleconemenu中刪除了'disabled',所以它總是呈現,然後當測試時,我也從這個下拉列表中選擇了一個,如果ajax更新被調用,它會重置這個選擇,它會這樣做。因此,總而言之,每次調用ajax render'addState時,只有address.country的值在第二次選擇前纔會更新。 – Ectomorph