views:

458

answers:

3

Is it posssible to have the previous value of checkbox alongwith new value?

My problem is, i have to execute some code, only if the value of checkbox is true, also if it was already true, then i am not suppose to perform the same action again. Currently what i am doing is , for every checkbox i am having previous value holder too. If the value is changed only then i perform the action ( and it is true ), and set value of previous value holder to the new value.

A: 

You can add a change listener to the checkbox. When the checkbox changes the state, you can directly call your special code.

Or when you have a preference page, in which the checkbox is inside, you have to store the state of the preference page and check, if you have changed states inside.

Markus Lausberg
A: 

Are you using the spring mvc JSP tablib or velocity/freemarker macros?

If you are, they should be ouputting a hidden field with the existing value of the checkbox in the HTML with an underscore "_" in front of it. Spring does this to help determine whether the checkbox was unchecked or just not submitted.

You should be able to appropriate this hidden field for your purposes, i.e. you can check for the value of the hidden field and compare it to the actual checkbox field value.

See Spring MVC 2.5 Checkbox tag

Rob Beardow
A: 

To do this properly you will need to do the comparison without relying on the client side to record the old value as this could allow tampering.

On submit, Spring MVC rebuilds the old version of the command before updating it with the new values submitted from the client. You will need to save the old value somewhere before the bind phase begins.

To do this, in the formBackingObject method (which gets called again after a POST submit), put a copy of the value in the request object. Then in the onSubmit method, you can retrieve the value from the request for the comparison. You could also record it in a different field on the command.

I find this SimpleFormController cheat sheet very helpful for figuring out the execution order of the methods. It should help you out here too.

Donal Boyle