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;
}
}