Using FieldSet with Visualforce and Apex

One of the disadvantages comes up with Custom Page or Overriding New or Edit button with Visualforce page is its “Maintenance”, if New Filed is Added or needed to remove field we have to modify our code every time.

However, Thanks to Salesforce that we have “Field Set“.

With the Help of “Dynamic Visualforce Binding” and “Field Set” we can create effective Visualforce pages with ability to change Fields and its Sequence any time without modifying any code.

Let’s start with using Field set in Salesforce.

Step 1: Creating Field Set

First we need to create a field set. For this article, I am using custom object named “Question__c”.

We have to navigate to setting page of that object and then “Field Sets”. Create a new Field Set and add required field in Sequence as displayed in below image.

Create Field Set in Salesforce
Create Field Set in Salesforce

Assume that field set name is “Add_Question”.

Salesforce Interview Question – Part 14

131. What will happen if you try to update record in After Trigger Context?
Ans : You will get an error saying “record is Read only”.

132. Let’s say we have to update the same record in After Trigger context. Is there any way or workaround?
Ans : If we create a new instance of an SObject in the Apex Trigger in memory using the Id of the newly created record as provided in the After Trigger context, we can perform an Update DML statement and not get a read only error. This is because in Apex, the SObject is seen as a new reference (even though the records have the same SFDC ID) and therefore is eligible for DML operations. The below snippet of code illustrated this working and not working.

List<Contact> originals = new List<Contact>();
if(mirrorResultMap.values().size() > 0)
	for(Contact origContact : contactRecs.values())
		Contact mirrorContact = mirrorResultMap.get(origContact.Id);
		//origContact.Linked_Contact__c = mirrorContact.Id; //Link the Original Record tot he Mirror Record WILL FAIL
		Contact origContactUpdate = new Contact(Id=origContact.Id, Linked_Contact__c = mirrorContact.Id); //This will WORK
	//update contactRecs.values(); //Update the Records -> THIS WILL FAIL AS ITS ORIGINAL RECORDS IN MEMORY
	update originals;

Credit goes to Cory Cowgill for this Blog Entry.

133 . When loading data into date fields such as Opportunity Close Date using the Data Loader, the date displayed in the application is sometimes one day earlier than the date in the file. What may be the reason and solution ?
Ans :
The reason for this is that fields such as Close Date are actually date/time fields. When a date is loaded without specifying the time, the time is defaulted to 00:00 – midnight. When another user is in a time zone which is behind the current user’s time zone, the date will show on the previous day. For example:

20 August 2008 00:00 in Paris is 19 August 2008 23:00 in London

Similar issues can arise when daylight savings time begins or ends.

Two simple solutions to this are:
1) Specify a time as well as a date when loading dates using the Data Loader.
2) Switch your PC’s time zone to Hawaiian time before starting up the Data Loader.

How to Debug Manage Package in Salesforce

Many times as a developer we need to debug the manage package for possible run time error. For example , while uploading contacts using Import wizard we get “Internal Server Error” and when we try to look into debug log there is no clear indications. However in my experience i have seen this kind of error may be because of manage package installed from AppExchange. As per “Intellectual property” rights , Salesforce cannot show the debug logs to everyone, However there is one way to achieve by System admins to some extent.

For purpose of this article, i am using one manage package from AppExchange to show how it works.

Merge PDF in Salesforce Using Java, ITextPDF and OAuth 2

Its long time, since i wrote any article because of my busy schedule However this time i came with advance one. In this article we are going to use the J2EE (Servlet) to Merge PDF attachment inside salesforce with the help of OAuth and ITextPDF jar file. The reason of writing this article is that there is no native support by Apex to merge two attachments in Salesforce. Either we have to go for AppExchange product like CongaMerg or Drawloop or we can write our own code in any other language like Java and C# and with the help of REST API we can save get and save attachment in Salesforce.

First we will need to setup the OAuth permission so that our local J2EE application can interact with Salesforce. For this login to Salesforce account and Navigate to “Set up | App Set up | Develop | Remote Access” and enter the information. Be careful about the “Callback URL”. It must match in your code. After creating the “Remote Access”, note “Consumer Key” and “Consumer Secret” which will be needed in your code.

Update : “Remote Access” is renamed to Connected App. So throughout this article, if you see image of “Remote Access” then please consider it as Connected App.

Create Remote Access in for OAuth 2
Create Remote Access in for OAuth 2

How to Sort Wrapper class Collection in Apex

There is inbuilt functionality in Apex to sort the primitive datatypes supported by I am sure maximum of developers must have come across the situations where they need to sort custom datatype built by them i.e. custom class or I would say wrapper class in terms of

But think, How will come to know that how to sort class? In case of integer, date or double they already know. But how they are going to know that what is going to be content in your class? Before Summer’12 there was no direct way. However thanks to Salesforce to introduce the interface Comparable in Summer’12 release. And… there is smile on the face of Java developers, because they already know what it is.

So let’s start with “What is the use of interface Comparable?“ I would say, this is the way to tell that how we are going to compare the custom Objects (Wrapper class).

Comparable Interface:

To implement the Comparable Interface, you must declare global class with the implements keyword as follow:

Apex based record sharing in Salesforce

Last update : May 4 2020

There are situations where the business requirement is too complex and standard sharing rules provided by the Salesforce will not work.

Example: On Opportunity, you want to give access to record to some users which are in related list.
One way is to manually share the record which will need the interference of opportunity owner. But everyone will love automated solution.

Apex managed sharing provides developers with the ability to support an application’s particular sharing requirements programmatically via Apex code.

Before you proceed, few points to note about Apex based sharing

  • Share table available only when Organization Wide Default [OWD] sharing is not Public Read Write
  • Apex sharing reasons can be created only for custom objects
  • As Apex Sharing Reason not available for Standard objects only way to create Apex based sharing for Standard objects are using row cause Manual
  • As row cause is Manual for Standard objects, Apex based sharing would be lost once owner is changed [Because its behavior of Manual Sharing]
  • In case of custom object & custom Apex Sharing Reason, sharing would not be lost when owner changed
  • Read more in detail from official documentation

Pre requisite:

The object’s organization-wide default access level must not be set to the most permissive access level. For custom objects, this is Public Read/Write. For more information, see Access Levels. This object is used for creating Apex based sharing.

The user to which the record going to be shared must have the object level permission. If you are trying to share the record with edit permission but user does not have the edit permission on that object, then it will not work.

To access sharing programmatically, you must use the share object associated with the standard or custom object for which you want to share. For example, AccountShare is the sharing object for the Account object, ContactShare is the sharing object for the Contact object, and so on. In addition, all custom object sharing objects are named as follows, where MyCustomObject is the name of the custom object: “MyCustomObject__Share”.

Objects on the detail side of a master-detail relationship do not have an associated sharing object. The detail record’s access is determined by the master’s sharing object and the relationship’s sharing setting.

In this article I want to share the custom object “Test__c” with students. Let’s consider that every “Test” has lookup to the “Student”.

APEX based DDP generation using LOOPlus

To automate the document generation in salesforce, we have two well known AppEchange products named “Conga Composer” and “LOOPlus from DrawLoop“. Both products are well used in industry and both have advantages and disadvantages over the need and situation.

This article depicts automating the document generation using Apex in LOOPlus. As i have been through this situation and didn’t find any resource on web to automate the document generation using Apex, so i thought to put this article.

Advantage of LOOPlus over Conga Composer:

  • The one advantage which i know is that using LOOPlus you can combine all the attachments into single one which is not possible in Conga Composer.

Navigate to this URL to install the trial version of Drawloop (LOOPlus) from AppExchange.

To use the Drawloop API we need to use the “Business” version of LOOPlus. To activate this, navigate to “LOOP” app and then “DDP Admin”. Click on button “Modify Subscription services“. New Page will open, select “Business” in LOOPlus level as shown in below image.

Enabling Business Version of DrawLoop
Enabling Business Version of DrawLoop

Introduction to View State in Visualforce

As we know that http protocol is stateless protocol. Unlike Other programming languages like Java and C# the variables, objects are persisted between different method and network calls. However in case of server client model, the server only stores the session related information of client, however it does not stores the temporary data being used by the clients. Sometime hidden field values, IDs and other information are needed by server for processing.

For example : If client needs any data and is loaded by the server in first request, if error comes the server will need to retrieve data again for second request. Also it is possible that few data is created at client side also, so to persist the state of client View State is used in Visualforce.

Before Summer 12, For every form tag the View State was created. However from Summer 12 release only one View State will be created per page. View State is encrypted and transferred to client with each response. View State cannot be viewed with tools like firebug however salesforce has “View State Inspector” to check the View State Data.

Types of Data Saved in View State:
Following data are saved in Viewstate

  1. All public and private data members present in Standard, Custom and Controller extensions.
  2. Objects that are reachable from data members in Custom and Controller extensions.
  3. The component tree for that page that represents the page’s component structure and the associated state which are the values applied to those components.
  4. Small amount of data needed by visualforce for other general purposes.

Transient Variable and Objects:
As Viewstate is transferred over http with every response, it is very necessary to control the size of View State. There are lots of situations where data is not needed after postback or not needed on Visualforce page then in that case we can make variable or object transient. The transient variables are not passed to view state and therefore not stored in View State.

Method Parameters – Pass by Value or Pass by Reference

This topic has always been part of discussion where the answer is not satisfactory and convinced to others. Using this article, I will try to explain the concept of parameter passing in Apex Method. This Complete topic is applicable for Java or other programming languages as well.

Before moving ahead let’s have a summary on what is pass by value and pass by reference.

Pass by value means when a method is called, a second copy of the parameter variable is made in memory, and this copy is passed to the method as a parameter. This copy can be modified in the method, but the original variable in the caller is unchanged, and the changes to the copy are lost upon return.

Pass by reference means when a method is called, that actual variable is passed to the method.

Million dollar question: parameters in method are passed by value or pass by reference?
Most of answers: primitive data types like Integer, Double are pass by value and Objects are pass by reference.

However, the above statement is not 100% true. I know I just invited controversy on this post. Be Patient with me and I would prove with actual example, feel free to run these examples in your Developer Console.

Correct Answer: parameters are passed by value in Apex as well as in Java. Where, in case of object the copy of reference is first made and then passed, therefore we can change the fields of object inside method however we cannot change the Object itself.

Take a pause here and think what I just said. I’m saying, new variable copy created which points to same Object. So, it seems reference but variable technically itself is storing value which is address or reference of object.

Let’s discuss this in more detail. I am going to explain two scenarios in which I will try to change the field value and in second example I will try to change Object itself.

Example 1

Account a = new Account(); 
a.Name = 'Shivasoft'; 
a.Website = ''; 
System.debug('Website - '+a.Website); 

public void changeWebsite(Account b) { 
    b.Website = ''; 

Output of above code is

Website -

What just happened in Example 1

Salesforce Pass by Value or Pass by Reference - Scenario 1
Salesforce Pass by Value or Pass by Reference – Scenario 1

As per code snippet, the object a is supplied in method changeWebsite(). The parameter is actually passed by value, where the copy of value a is passed to object b which is memory address (aka reference). As we can see that both variable have reference of same object and hence whatever changes done by variable b on that object it will be applicable for variable a also.

If you are still not convinced and think I’m wrong, wait for example 2.

Example 2

Account a = new Account(); 
a.Name = 'Shivasoft'; 
a.Website = ''; 
System.debug('Website - '+a.Website); 

public void changeWebsite(Account b) { 
    //Create New Object and try to replace old 
    b = new Account();
    b.Website = ''; 

Before I go further and reveal answer, let’s think what would be output ?

If you assumed method parameters are passed by reference then output should be

Website -

However actual output is

Website -

What just happened in example 2 ?

Salesforce Pass by Value or Pass by Reference - Scenario 2
Salesforce Pass by Value or Pass by Reference – Scenario 2

As per code snippet, the object a is supplied in method changeWebsite(). Like I said, the parameter itself is actually passed by value, where the copy of value a is passed to object b which was reference. As we can see that both variable had reference of same object initially. However, inside the method new object is created and reference assigned to b and just now important event occurred. Refer above image for clear explanation

Previously b was pointing to old object, if it was really reference then it should impact object a. However now a and b variables point to different object. Whatever the changes done inside method, it will not be reflected outside as object a still have old reference. And hence after method execution when we check the value of object a, it is not affected because of method execution.

Salesforce documentation says :

“In Apex, all primitive data type arguments, such as Integer or String, are passed into methods by value. This means that any changes to the arguments exist only within the scope of the method. When the method returns, the changes to the arguments are lost.
Non-primitive data type arguments, such as sObjects, are also passed into methods by value. This means that when the method returns, the passed-in argument still references the same object as before the method call, and can’t be changed to point to another object. However, the values of the object’s fields can be changed in the method.”

Time for Best Practice

Because of behavior of parameters are passed as a value, it is always best practice to return object back to calling method. JUST DON’T ASSUME that object is passed by reference and whatever happened inside method will reflect calling method.

So code would become

Account a = new Account(); 
a.Name = 'Shivasoft'; 
a.Website = ''; 
a = changeWebsite(a); 
System.debug('Website - '+a.Website); 

public Account changeWebsite(Account b) { 
    //Create New Object and try to replace old 
    b = new Account();
    b.Website = ''; 
    return b ;

Salesforce Apex Code talk – Important Questions and Answers

Hello everyone,
On 24th April 2012, There was Apex code chat conducted by the Salesforce. So i thought to share important question and answers of that chat. You can read complete chat here.

Here are some of the (edited) highlights from this episode’s chat transcript.

Question: Is there a way in Apex to send an email and replace the default from email address (
Ans: Yes, using either the setSenderDisplayName or setOrgWideEmailAddressID methods on the SingleEmailMessage or MassEmailMessage classes.

Question: Which fields are accessible in a record without performing a SOQL query? For example if my trigger is on the Contact object, are fields on the parent Account object (like Account Description) accessible without performing an explicit SOQL query?
Ans: You can use to access all non-null fields of the object on which the trigger is defined. You have to perform an explicit SOQL query to access any fields on associated parent or child records. For example, if the trigger is defined on Contact, you can only access the Id of the parent Account record (via AccountId) in You’d need to perform a separate SOQL query to access any other field on the parent Acccount record (e.g. Description, Industry etc.).