PDA

View Full Version : Common coding mistake with FieldBinding



jadrake75
22 Mar 2011, 9:24 AM
There is an issue I have run across a few times which has been a pain to diagnose and has often caused me to lose valuable time debugging to resolve. I think there is an easy resolution to this.

I am using BeanModels from a backing POJO. I then have FormPanels in which I am binding a field to a value in the model (which is a bean model).

The setup for this would be something like this:

POJO:


public class PreferenceValue {
String value;
public String getValue( ) {
return value;
}

public void setValue(String value) {
this.value = value;
}
}


In this example, my POJO store's the preference value as a string (and provides accessor methods to get the value as a int, double, boolean etc.). But for the issue I am describing the key point is the return type of the field's value must be different than the bean value's type.

This bean would be converted to a BeanModel using the BeanModelFactory ..... and the binding would be something like the following:



NumberField nf = new NumberField ();
nf.setAllowNegative(false);

FormBinding percentageBinding = new FormBinding(getFormPanel());
FieldBinding pb = new FieldBinding(nf, "value");
percentageBinding.addFieldBinding(pb);
percentageBinding.setStore(getListStore());
// do more setup and at some point...
percentageBinding.bind(beanModel);


ok, so change events will be propagated to the BeanModel via the Record (since we are using a store) and it will attempt to set the "value" to whatever was entered (say 0.456 since it is a NumberField). In line 286 of Record, the call to



model.set(name, value);


will cause an exception. This is because the value in the binding is a number, but the underlying bean property is cast as a string.

Ok, so the fix to this is create a converter which converts the numeric value from the number field to a string, and conversly can convert the string to a number. Of course this is IF you remember to do this. If you do not do this an exception is caught in the SimpleEventBus (GWT class) and is essentially buried (no stack trace or any other notice).
Since the binding is happening as your make updates to your field, it can be several clicks/steps/seconds later that you actually process the updates (such as submitting) only to find out your fields are not being processed/sent on the bean.

Since I have been caught by this a few times (about once every three months) do you think it might be worthwhile to at least look for and print/dump the exception either at the record.set() method or perhaps within the updateModel() method of the FieldBinding class? From a developer productivity perspective this would be a big savings....

Thoughts?