2
votes

I'm new to JSF, so this question might be strange. I have an inputText component's value bound to managed bean's property of type Float. I need to set property to null when inputText field is empty, not to 0 value. It's not done by default, so I added converter with the following method implemented:

public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) throws ConverterException {
 if (StringUtils.isEmpty(arg2)) {
  return null;
 }

 float result = Float.parseFloat(arg2);
 if (result == 0) {
  return null;
 }
 return result;
}

I registered converter, and assigned it to inputText component. I logged arg2 argument, and also logged return value from getAsObject method. By my log I can see that it returns null value. But, I also log setter property on backing bean and argument is 0 value, not null as expected. To be more precise, it is setter property is called twice, once with null argument, second time with 0 value argument.

It still sets backing bean value to 0. How can I set value to null?

Thanks in advance.

2

2 Answers

3
votes

I know this is an old post, but it helped me. I wanted to add a snippet of code that seems to work for in my webapp to set the variable that BalusC mentioned without having to supply it as a VM argument:

public class ServletContextListenerImpl 
        implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent event) {
        System.getProperties().put(
            "org.apache.el.parser.COERCE_TO_ZERO", "false");
    }
}

I can't guarantee that the people who deploy my webapp will properly add the VM arguments to the Tomcat 6 startup script, so I feel safer embedding it in my webapp code. This made the problem go away for me. I'm using Apache MyFaces JSF 1.2.

In my webapp, the problem was a Double field on the backing bean that kept getting assigned the value 0.0 instead of null.

2
votes

When returning null in getAsObject(), you need to set the component's submitted value to null as well.

if (result == null) {
    ((EditableValueHolder) component).setSubmittedValue(null);
}

There is however an environment specific issue with this, namely the fact that the EL parser in Tomcat 6.0.16 or newer will still coerce this value as 0 in the view side even though when getAsString() returns null. You can go around this by adding the following line to Tomcat's VM arguments:

-Dorg.apache.el.parser.COERCE_TO_ZERO=false