[SalesForce] Apex inputText bound to integer takes 0 instead of null

My VF page below

<apex:page>
    <apex:form>
        <apex:inputtext value="{!num}" />
        <apex:commandbutton value="Save" action="{!saveFunction}"/>
    </apex:form>
</apex:page>

My controller

public with sharing class cls_updateCAPAccounts {
    public Integer num{get;set;}
    public void saveFunction(){
        System.debug('num:'+num); 
    }
}

When I send empty value in my inputtext, it is sent as 0. Can anyone tell me how I can pass null value from the page. It looks like it takes this 0 as default value since it is an integer but I want to send null values too.

Best Answer

apex:inputText will always send a string to the controller's setter.

If the setter is associated with an Integer type, SFDC will convert the empty string to 0.

If you want to test for null, make the setter type String and test for empty string via : String.isEmpty(..). If not empty, you can then do an Integer.valueOf(..) to get an Integer value elsewhere in your code. You will also need to validate against alphas (and, depending on your application, negative numbers).

Note that if you continue to use an Integer-type setter, then VF will handle type conversion errors such as alphas into integer and will display an error to the user. But empty string will be sent as 0.

Related Topic