Managed bean property value not set to null
I'm new to JSF, so this question might be strange. I have an inputText component value associated with a managed bean of type Float. I need to set the property to null when the inputText field is empty and not 0. This is not done by default, so I added a converter using the following method:
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 the converter and assigned it to the inputText component. I registered the arg2 argument and also registered the return value from the getAsObject method. From my log, I can see that it is returning null. But I also write the setter property backed by the bean and the argument is 0 and not null as expected. To be more precise, this setter property is called twice, once with a null argument, the second time with a 0 argument.
It still sets the bean to 0. How do I set the value to null?
Thanks in advance.
a source to share
When returning null
to, getAsObject()
you need to also set the value represented by the component to null
.
if (result == null) {
((EditableValueHolder) component).setSubmittedValue(null);
}
However, there is an environmental issue, namely the fact that the EL parser in Tomcat 6.0.16 or later will still coerce this value as 0 on the view side, even if it getAsString()
returns null
. You can work around this by adding the following line to the Tomcat VM arguments:
-Dorg.apache.el.parser.COERCE_TO_ZERO=false
a source to share
I know this is an old post, but it worked for me. I wanted to add a piece of code that seems to work in my webapp to set the variable mentioned by BalusC 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 cannot guarantee that people who deploy my webapp will correctly add VM arguments to the Tomcat 6 startup script, so I feel safer to nest it in my webapp code. This made the problem go away. I am using Apache MyFaces JSF 1.2.
In my webapp, the problem was a bean based double field getting assigned value 0.0 instead of null all the time.
a source to share