Category Archives: Salesforce

Redirecting Back to Previous Page Using Visualforce Page StandardController

Visualforce Page Button:

<apex:commandButton action="{!back}" value="Back"/>

Apex Controller:

public with sharing class ExampleController
{
    private ApexPages.StandardController sctrl;
    public SaveAndReturnController(ApexPages.StandardController stdController)
    {
        this.sctrl = stdController;
    }
 
    public PageReference back()
    {
        PageReference cancel = sctrl.cancel();
        return cancel;
    }
}

Add Fields in ApexPages.StandardController

If you want any fields value then you need add the field API name in standard controller.

public with sharing class AccountControllerExt
{
	public Account acc {get;set;}
	 
	public AccountControllerExt(ApexPages.StandardController stdController)
	{
		stdController.addFields(new List<String>{'Name', 'Region__c', 'TAX_ID_Number__c'});
		this.acc = (Account)stdController.getRecord();
	}
}

apex:inputfile ‘FileName’ and ‘Blob’ value being set null

Attachment Upload Controller:

public with sharing class AttachmentUploadController {
 
  public Attachment attachment {
  get {
      if (attachment == null)
        attachment = new Attachment();
      return attachment;
    }
  set;
  }
 
  public PageReference upload() {
 
    attachment.OwnerId = UserInfo.getUserId();
    attachment.ParentId = '0010E00000CxfKm';//Record Id the file is attached to
    attachment.IsPrivate = true;
    attachment.ContentType = 'image/jpeg';
 
    try {
      insert attachment;
    } catch (DMLException e) {
      ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'Error uploading attachment'));
      return null;
    } finally {
      attachment = new Attachment(); 
    }
    ApexPages.addMessage(new ApexPages.message(ApexPages.severity.INFO,'Attachment uploaded successfully'));
    return null;
  }
} 

Attachment Upload Visualforce Page:

<apex:page controller="AttachmentUploadController">  
	<apex:sectionHeader title="Example" subtitle="Attachment Upload Example"/>
	<apex:form>
	<apex:pageMessages />
		<apex:pageBlock title="Upload a Attachment">
			<apex:pageBlockButtons >
				<apex:commandButton action="{!upload}" value="Save"/>
			</apex:pageBlockButtons>
			<apex:pageBlockSection showHeader="false" columns="2">
				<apex:pageBlockSectionItem >
					<apex:outputLabel value="File Name" for="fileName"/>
					<apex:inputText value="{!attachment.name}" id="fileName"/>
				</apex:pageBlockSectionItem>
				<apex:pageBlockSectionItem >
					<apex:outputLabel value="File" for="file"/>
					<apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>
				</apex:pageBlockSectionItem>
			</apex:pageBlockSection>
		</apex:pageBlock>
	</apex:form>
</apex:page>  

Use enctype="multipart/form-data" in apex:form tag, when your form includes any apex:inputfile element.

<apex:form enctype="multipart/form-data">