2

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.

2

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.

| improve this answer | |
1

Try using an <apex:inputField> rather than an apex:inputText

This will enforce the type settings of the field.

| improve this answer | |
  • 1
    Didn't understand the alternative that you are suggesting. Can you kindly elaborate. – Saranya Jan 26 '15 at 14:13
  • I have added some code formatting to Kevin's answer so that it displays correctly. FYI apex:inputField is only for fields on SObjects so it can not be used here – BarCotter Jan 26 '15 at 14:20
  • Can he use that? inputField has to be bound to an sObject field, and his code says it's not. – PartOfTheOhana Feb 18 '17 at 23:04
  • No, i can't use it. Oh the stupidity of youth. Since it's not part of an subject, I'd have to use input, not inputfield – Kevin P Feb 21 '17 at 13:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.