Tag Archives: Force.com

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;

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;
  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:pageMessages />
		<apex:pageBlock title="Upload a Attachment">
			<apex:pageBlockButtons >
				<apex:commandButton action="{!upload}" value="Save"/>
			<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:outputLabel value="File" for="file"/>
					<apex:inputFile value="{!attachment.body}" filename="{!attachment.name}" id="file"/>

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

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

Copy Billing Address to Shipping Address in Salesforce Visualforce Page

<apex:page standardController="Contact" extensions="ContactExtn" id="pgContact">

    <script type="text/javascript">
        function copyAddress() {
            // Variables for Billing Address
            var copy_BillingPostalCode = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBPostalCode').value;
            var copy_BillingAddress1 =document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBAdd1').value;
            var copy_BillingAddress2 = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBAdd2').value;
            var copy_BillingAddress3 = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBAdd3').value;
            var copy_BillingCity = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBCity').value;
            var copy_BillingState = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBState').value;
            var copy_BillingCountry = document.getElementById('pgContact:fmContact:pbContact:pbsBillingAdd:ifBCountry').value;
            // Copying the Billing Address to the Shipping Address
            if(copy_BillingPostalCode != null)
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSPostalCode').value = copy_BillingPostalCode;
            if(copy_BillingAddress1 != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSAdd1').value = copy_BillingAddress1;
            if(copy_BillingAddress2 != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSAdd2').value = copy_BillingAddress2;
            if(copy_BillingAddress3 != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSAdd3').value = copy_BillingAddress3;
            if(copy_BillingCity != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSCity').value = copy_BillingCity;
            if(copy_BillingState != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSState').value = copy_BillingState;
            if(copy_BillingCountry != null) {
                document.getElementById('pgContact:fmContact:pbContact:pbsShippingAdd:ifSCountry').value = copy_BillingCountry;
    <apex:form id="fmContact">
        <apex:sectionHeader title="Contact Information" subtitle="{!Contact.Name}"/>
        <apex:pageBlock mode="Edit" id="pbContact">
            <apex:pageBlockSection showHeader="true" collapsible="false" columns="2" title="Billing Address Information" id="pbsBillingAdd">
                <apex:inputField value="{!Contact.Billing_Postal_Code__c}" id="ifBPostalCode"/>
                <apex:inputField value="{!Contact.Billing_City__c}" id="ifBCity"/>
                <apex:inputField value="{!Contact.Billing_Address_Line_1__c}" id="ifBAdd1"/>
                <apex:inputField value="{!Contact.Billing_State__c}" id="ifBState"/>
                <apex:inputField value="{!Contact.Billing_Address_Line_2__c}" id="ifBAdd2"/>
                <apex:inputField value="{!Contact.Billing_Country__c}" id="ifBCountry"/>
                <apex:inputField value="{!Contact.Billing_Address_Line_3__c}" id="ifBAdd3"/>
            <apex:pageBlockSection showHeader="true" collapsible="false" columns="2" title="Shipping Address Information" id="pbsShippingAdd">
                <apex:inputField value="{!Contact.Shipping_Postal_Code__c}" id="ifSPostalCode"/>
                <a HREF="#" onClick="return copyAddress();">Copy Billing Address to Shipping Address</a>
                <apex:inputField value="{!Contact.Shipping_Address_Line_1__c}" id="ifSAdd1"/>
                <apex:inputField value="{!Contact.Shipping_City__c}" id="ifSCity"/>
                <apex:inputField value="{!Contact.Shipping_Address_Line_2__c}" id="ifSAdd2"/>
                <apex:inputField value="{!Contact.Shipping_State__c}" id="ifSState"/>
                <apex:inputField value="{!Contact.Shipping_Address_Line_3__c}" id="ifSAdd3"/>
                <apex:inputField value="{!Contact.Shipping_Country__c}" id="ifSCountry"/>

Create One to One Relationship in Salesforce

Basically Salesforce offers two types of relationship:

  • One To Many Relationship
  • Many To Many Relationship (Using the concept of Junction object)

Sometimes we may need One To One relationship, But unfortunately Salesforce doesn’t allow any direct methodology to build One To one relationship.

Let’s consider the scenario that we want to establish a One to One relationship between two custom objects Employee__c and PAN_Card__c.

So, here are few ways to implement One To One relationship between two objects in Salesforce. We can achieve this by using configuration only and can also achieve this by using code to make it more scalable.

Option 1:

  • Create a lookup field on PAN_Card__c to Employee__c.
  • Create a custom field on the PAN_Card__c object and make the field unique. This field would be used to hold the ID of the associated Employee__c. Hide this field from all page layouts.
  • Create a Workflow rule on PAN_Card__c. For any change of the lookup field on PAN_Card__c object, update the custom field on the PAN_Card__c object with the value of the associated Employee Id.

We have established a one to one relationship between PAN_Card__c and Employee__c. When we try to add a second PAN_Card__c to the Employee__c, the “unique” constraint would be violated and an error would be thrown. This approach will work on both standard and custom object.

Option 2:

  • Create a master detail relationship on PAN_Card__c to Employee__c object.
  • Create a roll up summary field on Employee__c object of PAN_Card__c with count type.
  • Create a validation rule on Employee__c object rollup summary field to check if count > 1.

In this way also, We have established a one to one relationship between PAN_Card__c and Employee__c. So it will throw an error if Employee__c has more than one PAN Card.

Option 3:

  • Create lookup fields on both objects PAN_Card__c and Employee__c, to each other.
  • Write triggers, for any change on these lookups, to either copy the record ID into the other object’s lookup field when the other object’s lookup field is empty, or disallow the change to the original record when the other object’s lookup field is already populated with a different ID from the original record.

This is already having a one-to-onePassport relation.

Option 4:

  • Create a trigger on PAN_Card__c object to check if the PAN Card record already exists for an Employee. If it exist, then throw an error, else allow the user to create.
    Here is the example for Employee__c and PAN_Card__c object:

    trigger PANCardValidation on PAN_Card__c (before insert, before update) {
        Set<id> employeeIds = new Set<id>();
        Map<id, Employee__c> mapEmployee = new Map<id, Employee__c>();
        for (PAN_Card__c p : trigger.New) {
        List<Employee__c> lstEmployee = [SELECT Id, Name FROM Employee__c WHERE Id IN : employeeIds];
        if (!lstEmployee.isEmpty()) {
            for (Employee__c emp : lstEmployee) {
                mapEmployee.put(emp.Id, emp);
            for (PAN_Card__c p : trigger.New) {
                if (mapEmployee.containsKey(p.Employee__c)) {
                    p.addError('A PAN Card already exist for the employee - ' + mapEmployee.get(p.Employee__c).Name);