0

I have developed a Visualforce page that takes an input file from the user and does not let the user proceed to the next page only if they did not upload an attachment (attachment is null). However I have discovered that because the attachment variable is instantiated in the getter method, the PageReference method cannot return null when triggered by the if statement - is there any way I can have the method return null so that the user cannot proceed to the next page unless they upload a file?

VF Page

<apex:page controller="Test_ExceptionClass">
    <div align="center">
    <apex:form>
    <apex:pageBlock>
        <apex:pagemessages></apex:pagemessages>
        <apex:outputLabel> Upload File</apex:outputLabel>
        <apex:inputFile value="{!att.Body}" fileName="{!att.Name}">
        </apex:inputFile>
    <apex:pageBlockButtons>
        <apex:commandButton action="{!nextPage}" value="Next"/>
    </apex:pageBlockButtons>    
    </apex:pageBlock> 
    </apex:form>
    </div>
</apex:page>

Controller

public class Test_ExceptionClass {

    public Attachment att{
        get{
            if(att == Null)
                att = New Attachment();
            return att;            
        }
        set;
    }
    
    public Test_ExceptionClass(){
        //Empty constructor
    }
    
    public PageReference nextPage(){
        
       PageReference pageRef = Page.Test_Exception2;
       PageRef.setRedirect(false);
        if(att == null){
        ApexPages.addMessage(
        new ApexPages.Message(
        ApexPages.Severity.ERROR,
        'You need to have an attachment first.'
        )
     );
        return null;
        }   
      
       return Page.Test_Exception2;
    }
}

1 Answer 1

2

you could always check for the attachment body or name - your att variable might never be null, but body and name might be.

4
  • Thanks. How could I check for this?
    – SpicyPat
    Commented Apr 3, 2021 at 20:19
  • 1
    just check att.Name or att.Body in your if. Commented Apr 3, 2021 at 20:20
  • You're a genius! Thanks buddy! My client will be happy :)
    – SpicyPat
    Commented Apr 3, 2021 at 20:24
  • 1
    naah, you've just entered tunnel thinking. That happens in our job :) Pleased to help you! Commented Apr 3, 2021 at 20:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .