Binding with type Integer how to convert empty string to null

Hello

I have the following situation (credits is from type Integer)

Subscription subscription = new Subscription();
BeanItem<Subscription> subscriptionItem = new BeanItem<Subscription>(subscription);
Property creditProperty  = subscriptionItem.getItemProperty("credits");
TextField creditText = new TextField("Credits", creditProperty);

I ask me how I can convert the empty string to null if someone enters an empty string into the TextField creditText. I have seen in Vaadin 7 there exists a method called setConverter and with this method I could handle the entered input how I wish. But how to handle this in Vaadin 6?

Thank you for any hint.
chris

Hi Christian,

you can use TextField.setNullRepresentation("");

So, when the user type an empy string, it will be converted to null.
A null value for the propertyDataSource.getValue() will be rendered as empty string too.

Hope it’s help

regard,

Éric

Hi Eric

Thank you for your reply and apologize my late answer. Actually I use setNullRepresentation already but this does not solve my problem. What i get is:

java.lang.NumberFormatException: For input string: “”

I guess because credits is from type Integer vaadin tries to do a conversion. But it shouldn’t do it if an empty string is entered by the user.
If I could change to a own converter I could solve it, but I’m not sure how I can do it with vaadin 6. I know vaadin 7 supports such a method, but what with vaadin 6?

Let me know if you have any hint.

br
chris

Vaadin 6 does not have any Converters. But you can solve this by writing your own Property-Implementation (That’s not too hard, just try it).

Or use PropertyConverter (and possibly FieldWrapper) from the
CustomField add-on
.

Thanks Guys

I could solve it with a own FieldWrapper. In case someone else has the same problem. Here the source:

import org.apache.commons.lang3.StringUtils;
import org.vaadin.addon.customfield.FieldWrapper;

import com.vaadin.ui.Field;
import com.vaadin.ui.Layout;
import com.vaadin.ui.VerticalLayout;

@SuppressWarnings("serial")
public class IntegerField extends FieldWrapper<Integer> {

	public IntegerField(Field wrappedField, Class<? extends Integer> propertyType) {
		super(wrappedField, propertyType);
		Layout layout = new VerticalLayout();
		layout.addComponent(wrappedField);
		setCompositionRoot(layout);
	}
	
	@Override
	protected Integer parse(Object formattedValue) throws ConversionException {
		if (formattedValue == null || StringUtils.isBlank(formattedValue.toString())) return null;
		String input = formattedValue.toString();
		try {
			return Integer.parseInt(input);
		}
		catch (NumberFormatException e) {
			return null;
		}
	}
}