What are two ways that a controller and extension can be specified on a Visualforce page

In this module, you enhance the Visualforce page you built in module 7: you create a controller extension that allows users to upload speaker pictures.

What are two ways that a controller and extension can be specified on a Visualforce page

Step 1: Extend the Data Model

In this step, you add two fields to the Speaker object: Picture_Path to store the location of the picture on the server, and Picture, a Formula field used to display the image in the Visualforce page.

  1. In Setup, select Build > Create > Objects, and click the Speaker link

  2. In the Custom Fields & Relationships section, click New, and create a Picture_Path field defined as follows:

    • Data Type: Text
    • Field Label: Picture Path
    • Length: 255
    • Field Name: Picture_Path

    Click Next, Next, Save & New

  3. Create a Picture field defined as follows:

    • Data Type: Formula
    • Field Label: Picture
    • Field Name: Picture
    • Formula Return Type: Text
    • Formula: IMAGE(Picture_Path__c, '')

      Make sure you use two single quotes and NOT a double quote.

    Click Next, Next, Save

Step 2: Create a Controller Extension

  1. In the Developer Console, select File > New > Apex Class, specify SpeakerControllerExtension as the class name and click OK

  2. Implement the class as follows:

    public class SpeakerControllerExtension { public blob picture { get; set; } public String errorMessage { get; set; } private final Speaker__c speaker; private ApexPages.StandardController stdController; public SpeakerControllerExtension(ApexPages.StandardController stdController) { this.speaker = (Speaker__c)stdController.getRecord(); this.stdController = stdController; } public PageReference save() { errorMessage = ''; try { upsert speaker; if (picture != null) { Attachment attachment = new Attachment(); attachment.body = picture; attachment.name = 'speaker_' + speaker.id + '.jpg'; attachment.parentid = speaker.id; attachment.ContentType = 'application/jpg'; insert attachment; speaker.Picture_Path__c = '/servlet/servlet.FileDownload?file=' + attachment.id; update speaker; } return new ApexPages.StandardController(speaker).view(); } catch(System.Exception ex) { errorMessage = ex.getMessage(); return null; } } }

    The save() method overrides the standard controller's default behavior.

  3. Save the file

Step 3: Modify the Visualforce page

  1. In the Developer Console, open the SpeakerForm page, and add the controller extension to the page definition:

    <apex:page standardController="Speaker__c" extensions="SpeakerControllerExtension">

  2. Add an inputFile (right after the Email inputField):

    <apex:inputFile value="{!picture}" accept="image/*" />

    Make sure you use an inputFile and not an inputField

  3. Display the potential errorMessage right after </apex:pageBlock>

  4. Save the file

Step 4: Test the Application

  1. Click the Speakers tab

  2. Click New to add a speaker

  3. Enter the speaker first name, last name and email

  4. Click the Choose File button and select a jpg file on your file system

  5. Click the Save button: you should see the image on the speaker's details page

A controller extension is a class of APEX that extends the functionality of a custom or standard controller. We use controller extensions:

  • When we want to add new functions.
  • When we want to use a default function and make a few changes in the functional flow.
  • When we want to build a VFP that applies for user permissions, even after a controller extension executes in system mode.

How extensions can help you build advanced Visualforce Pages?

As discussed in the previous articles, Extensions has several benefits, it can have standard & custom controllers. In Extension, we can have one standard or custom controller and can have multiple classes. There are various scenarios in which we can use the extension. 

Business Scenario

We have a business scenario in which the standard & custom extensions should be explained in the Visualforce Page and the DML including in the Visualforce Page also.

#Apex Class For Business Scenario:

public class MyControllerExtensionExample5Feb{ public static string message{get;set;} public static string VariableForStoringAccountName {get;set;} public MyControllerExtensionExample5Feb(ApexPages.StandardController stdController) { //write any code which u want to execute at the start } public static void ShowGreeting() { message = 'Welcome to Extension demo' ; } public void mysave() { Account NewAccount = New Account(); NewAccount.Name = VariableForStoringAccountName; NewAccount.industry = 'Chemical'; insert NewAccount; } }

What are two ways that a controller and extension can be specified on a Visualforce page

Steps to create a Visualforce Page:

Log in to Salesforce → Setup → Build → Develop → Visualforce Pages(Click on it) → Click on New button

#Code for creating a Visualforce Page:

<apex:page standardController="Account" extensions="MyControllerExtensionExample"> <apex:form > <apex:pageBlock title="Page Block 1"> <apex:pageBlockSection title="Page Block Section 1 | Custom Controller Example" Columns="2"> <apex:pageBlockSectionItem ><Apex:commandButton value="Greeting" reRender="id1" Action="{!ShowGreeting}"/></apex:pageBlockSectionItem> <apex:pageBlockSectionItem ><Apex:outPutLabel id="id1"> {!message} </Apex:outPutLabel> </apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> <apex:pageBlock title="Page Block 2"> <apex:pageBlockSection title="Page Block Section 2 | Standard Controller Example" Columns="2"> <apex:pageBlockSectionItem >New Company:<apex:inputField value="{!Account.name}" required="False" /></apex:pageBlockSectionItem> <apex:pageBlockSectionItem ><apex:commandButton value="Standard Save" action="{!save}"/></apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> <apex:pageBlock title="Page Block 3"> <apex:pageBlockSection title="Page Block Section 3 | Using Custom code For Save" Columns="2"> <apex:pageBlockSectionItem >New Company:<apex:inputText value="{!VariableForStoringAccountName}" /></apex:pageBlockSectionItem> <apex:pageBlockSectionItem ><apex:commandButton value="Custom Save" action="{!mysave}"/></apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>

Result:

What are two ways that a controller and extension can be specified on a Visualforce page

Explanation of the Code Step By Step - With different sections:

Section - Page Block 1 - Custom Controller Example

  • extensions="MyControllerExtensionExample" [Defines the Apex Class]
  • page standardController="Account" - [The account Name]
  • page block title="Page Block 1" - [The section title]
  • page block section title="Page Block Section 1 | Custom Controller Example" - [The heading of the section]
  • commandButton value="Greeting" - [The button name]

Checkout SalesForce Tutorial

On pressing the button available on the screen, it will hit the APEX class and retrieve the message saved in it.

What are two ways that a controller and extension can be specified on a Visualforce page

Section - Page Block 2 - Standard Controller Example

  • pageBlockSectionItem >New Company:<apex:inputField - [Filed input area]
  • value="{!Account.name}" - [Object in which the data is saved]
  • required="False" - [The data is mandate at the account field to override this we use this function]
  • commandButton value="Standard Save" - [Button name]
  • action="{!save}" - [On button press the data should be saved]

Note: By default, Objects has 2 things that are common, the data and the save, delete, edit, and other functions.

On button press, the data will be saved to the Default “Account” Object.

What are two ways that a controller and extension can be specified on a Visualforce page

DML in APEX Class - Section - Page Block 3 - Custom Controller Example

  • pageBlock title="Page Block 1" - [The section title]
  • pageBlockSection title="Page Block Section 3 | Using Custom code For Save" - [The heading of the section]
  • commandButton value="Custom Save" - [Button name]
  • action="{!mysave}" - [On button press the data should be saved]

Checkout Salesforce Interview Questions

Note: On button press, the code hits the Apex Class which is already saved by name “MyControllerExtensionExample5Feb” and with the variable name (binding between the Apex Class & Visualforce Page) “VariableForStoringAccountName”  and executes the code written in it and saves the data in Account Object.

What are two ways that a controller and extension can be specified on a Visualforce page

In the next topic, we will discuss in detail “Batch Class in Salesforce”. Keep following us for more info on Salesforce Development/Programming.

Explore Salesforce Sample Resumes! Download & Edit, Get Noticed by Top Employers!

Explore Salesforce Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download Now!

Mindmajix offers different Salesforce certification training according to your desire with hands-on experience on Salesforce concepts