Wednesday, June 24, 2009

Tapestry5 - How to dynamically populate a drop down list

Suppose you have 2 drop down lists - A & B
You want to populate the contents of B based on the selection in A
(For example: A = car manufacturer & B = car dealership)


In yourpage.tml


<t:form t:id="createAssetsForm">
<input t:id="selectManufacturer"/>
<input t:id="selectDealer" model="dealerSelection" />
</t:form>

<script>
function onManufacturerSelectFunction(response)
{
var selectDealer = document.getElementById("selectDealer");

// Unload the existing dealers
for (i = selectDealer.length; i != 0; i--) {
selectDealer.remove(i-1);
}

// Load the new dealers
for (i=0; i != response.dealers.length; i++){
var option = document.createElement('option');
option.text = response.dealers[i];
try {
selectDealer.add(option,null); // standards compliant
}
catch(ex){
selectDealer.add(option); //IE only
}
}
}
</script>


In yourpage.java
@Property
@Persist
private String manufacturer;

@Component(parameters = {"value=manufacturer", "model=literal:Honda, Toyota, Nissan, Subaru", "event=change",
"onCompleteCallback=literal:onManufacturerSelectFunction"})
@Mixins({"ck/OnEvent"})
private Select selectManufacturer;

@Property
@Persist
private String dealer;

@Component(parameters = {"value=dealer"})
private Select selectDealer;

@Property
@Persist
private SelectModel dealerSelection;


@OnEvent(component = "selectManufacturer", value = "change")
public JSONObject onTypeChangeEvent(String selectedManufacturer)
{
List<String> dealers = new ArrayList<String>();
... code to update dealers based on selectedManufacturer ...

// update the dealer selection
dealerSelection = TapestryInternalUtils.toSelectModel(dealers);

// IF you stop here - then the dealers will be updated only on page refresh!
// To update the dealers by AJAX (without page loading) do the following

// Pass the information to javascript as a JSON array
JSONArray JSONDealers = new JSONArray();

... code to enter the dealer names in the JSONArray ...

JSONObject json = new JSONObject();
json.put("dealers", JSONDealers);

return json;
}

No comments:

Post a Comment