31 July 2007

Neo-vintage: Checkboxes in Struts

This is a small tip, but for its awkwardness, I'm publishing here because there is no much information about it (although it's quite old).

Just it says in the Struts' API, we have to leave in false every checkbox in the form, if that Action has Session scope otherwise the checkboxes keep those values. The reset() method doesn't work for it (Listing 1).

The other trick is to use a dummy variable to keep the values from the form modified by the user, because when we are in the Action the values is lost in the checkbox and it can be changed based on this dummy variable updating on JSP by Javascript then in the Java code (Listing 2 & 3).





Este es un pequeño consejo, pero por su extrañeza, lo estoy publicando aca porque no hay mucha información al respecto (aunque es bastante viejo).

Como dice en el api de Struts hay que dejar en falso todos los checkboxes si ese Action es de scope de Session o si no se queda estaticos esos valores. El metodo reset() no funciona para tal caso.(Listing 1)

El otro truco es usar una variable auxiliar para mantener los valores desde el formulario modificado por el usuario, porque cuando estamos en el Action los valores se pierden en el checkbox y puede ser cambiado basandose en esta variable auxiliar actualizandola en el jsp a traves de javascript y despues en el codigo Java (Listing 2 & 3).

http://struts.apache.org/1.x/apidocs/org/apache/struts/action/ActionForm.html
http://husted.com/struts/tips/007.html



Listing 1
//let's assume we run through a collection of checkboxes, we have to assign to false
Collection contracts = (Vector)form.get("contracts");
Iterator it = contracts.iterator();
while (it.hasNext()) {
   Contract contract = (Contract)it.next();

   if(contract.isSelected()){
   //here we do our business, if the checkbox is selected

   ContractPdf cpdf = new ContractPdf();
   cpdf.setP_id_contract( (int)contract.getNum_contract() );
   //.... more code
}

//because it's a checkbox and has session scope we assign to false.
contract.setSelected(false);
}

Listing 2

//asign dummy values depending of checkbox
f = document.forms[0];

if (f.p_all.checked) {
   f.p_all.value = "ALL";
   f.p_all_dum.value = "on";
} else {
   f.p_all.value = "NONE";
   f.p_all_dum.value = "off";
}

Listing 3

//update the checkbox parameter based on the dummy variable on Java tier.
if("on".equals((String)formulario.get("p_all_dum"))){
   formulario.set("p_all", "ALL");
}else{
   formulario.set("p_all", "ALL");
}


No comments :

Blog Archive

Disclaimer

The views expressed on this blog are my own and do not necessarily reflect the views of Oracle.