Introduction to Exception Handling in Salesforce Apex

Introduction to Exception Handling in Salesforce Apex

Whenever you use a controller extension, extending a standard object, you can use the getRecord() to get the reference to the record. Most of us think that as soon as we call the getRecord() method, then the entire record is loaded into the contact variable. However, if you have an object with 1000 fields, and you only need to use 4 or 5 in your Visualforce pages, then does that make sense to load all the Fields on that Object? Think about it

hj

APEX CLASS:

public class RecordContactExt {
    private Contact contact;
    public RecordContactExt(ApexPages.StandardController sController) {
        this.contact = (Contact)sController.getRecord();
    }

    public String getCustomMessage() {
        return 'Aquaman, Wayne told the ' + contact.FirstName + ', “I believe that an enemy is coming from far away. ';
    }
}

VISUALFORCE PAGE:

<apex:page standardController="Contact" extensions="RecordContactExt">
    <apex:form>
        {!CustomMessage}
    </apex:form>
</apex:page>

Save it and Click on Preview. You will get something like this:

VB

Now refer the Id of the Contact whose data you want to display by appending?ID=0037F000001xxxx to the Header.

VB1

As soon as you will HIt Enter, you will get the following Error:

VB2

System.SObjectException: SObject row was retrieved via SOQL without querying the requested field: Contact.FirstName

Possible Solutions:

<apex:outputText value="{!contact.FirstName}"/>

If you don't want to display the contact name twice!!

<apex:outputText value="{!contact.FirstName}" rendered="false" />

or Use <apex:variable> instead, such as:

<apex:variable value="{!contact.FirstName}" var="contactFName" />

VB4

When you load this Visualforce page, the standard controller will scan through your Visualforce page and knows that you need this field, and when making the getRecord() method call, it automatically and implicitly adds this FirstName field into the SOQL.

Always remember, if you want to use any field in your extension via the getRecord() method, you need to let it be known by making sure that the field exists in your Visualforce page!

Another alternative is to write your own SOQL in your Apex class, but why make an extra SOQL call when you can avoid it?

31163A0400000578-3442108-image-a-27_1455189872679

"Great Leaders Make People See The Best Parts Of Themselves".

Responses

Comments are closed.

Popular Salesforce Blogs