Valuechangelistener Doubt in JSF -
hi,
please see following code:
<h:selectonemenu id="countries" value="#{countrybean.selectedcountry}" onchange="submit() valuechangelistener="#{countrybean.changecountry}"> <f:selectitems value="#{countrybean.countries }" /> </h:selectonemenu>
backing bean
public void changecountry(valuechangeevent event){ string newvalue = (string)event.getnewvalue(); string oldvalue = (string)event.getoldvalue(); system.out.println("new value : " + newvalue); system.out.println("old value : " + oldvalue); if ("1".equals(newvalue)){ this.countries = new arraylist<selectitem>(); this.cities.add(new selectitem("1","delhi")); this.cities.add(new selectitem("2","mumbai")); } if ("2".equals(newvalue)){ this.cities = new arraylist<selectitem>(); this.cities.add(new selectitem("1","mossco")); } }
please let me know if implementation correct. working fine. questions are:
- what advantage of adding f:valuechangelistener tag inside h:selectonemenu tag. have used normal attribute valuechangelistener="#{countrybean.changecountry}".
- is necessary use onchange="submit() code change values.
- what difference between writing custom listeners implementing actionlistener interface , using attribute in uicomponent tags (action="methodname"). please explain me.
the valuechangelistener
called when form submitted, not when value of input changed. thus, if want run listener when value modified, have 2 solutions:
- submit form when
onchange
event fired (this did in code); - use ajax call instead, using dedicated components (already integrated in jsf2,
<f:ajax>
, or third-parties libraries such richfaces, primefaces...).
here example richfaces:
<h:selectonemenu id="countries" value="#{countrybean.selectedcountry}" valuechangelistener="#{countrybean.changecountry}"> <a4j:support event="onchange" .../> <f:selectitems value="#{countrybean.countries }" /> </h:selectonemenu>
regarding code of listener, seems correct, why question why need valuechangelistener here? indeed, listener usefull when want track modification of value. that's why valuechangeevent
provides both getoldvalue()
, getnewvalue()
methods.
in code, not care old value, basically, "simply" action instead of valuechangelistener
(ex. richfaces):
<h:selectonemenu id="countries" value="#{countrybean.selectedcountry}"> <a4j:support event="onchange" actionlistener="#{countrybean.changecountry}"/> <f:selectitems value="#{countrybean.countries }" /> </h:selectonemenu>
finally, regarding difference between valuechangelistener
attribute , <f:valuechangelistener>
first binds java method (#{mybean.mymethod}
), while second binds java class (type="com.foo.mylistenerclass"
) implements valuechangelistener
interface. second 1 more generic first one...
Comments
Post a Comment