Visualforce in Salesforce
Visualforce is a framework in Salesforce used for building custom user interfaces. It allows developers to create dynamic and interactive web pages that run on the Salesforce platform, offering more flexibility compared to standard Salesforce layouts. Here's an overview:
Key Components of Visualforce:
- Visualforce Pages:
HTML-like markup language used to design the user interface.
Defined with the
<apex:page>
tag.Supports over 100 built-in Visualforce components like
<apex:form>
,<apex:outputText>
,<apex:inputField>
, etc.
- Apex Controllers:
Visualforce pages interact with Salesforce data via Apex controllers.
Types:
Standard Controllers: Prebuilt controllers for standard or custom Salesforce objects.
Custom Controllers: Custom Apex classes designed to handle complex logic.
- Visualforce Components
- Predefined UI elements like buttons, tables, and input fields.
Visualforce Variables
Use merge fields (
{! }
) to bind data dynamically from the controller to the page.Example:
{!Account.Name}
fetches the name of an account using a controller.
Where can you use visualforce:
Custom Tabs
Navigation Bar
As a component in Lightning App builder
App Page
Home Page
Record Page
Quick action
Override Standard buttons or links
Visualforce Page:
A Visualforce Page is a custom user interface (UI) built using the Visualforce framework in Salesforce. It is essentially an HTML-like web page that resides within the Salesforce platform and can include components, styling, logic, and data interaction.
- Example
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="Account Information">
<apex:pageBlockSection>
<apex:outputLabel value="Account Name:" />
<apex:outputText value="{!Account.Name}" />
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Visualforce Component:
A Visualforce Component is a building block used within Visualforce pages to define UI elements. Components encapsulate functionality and provide a simplified way to create complex UIs.
Types of Visualforce Components:
Standard Components
Predefined components provided by Salesforce.
Example:
<apex:outputText>
,<apex:inputField>
,<apex:commandButton>
.
Custom Components
- Developers can create reusable components using the
<apex:component>
tag.
- Developers can create reusable components using the
Examples of Standard Visualforce Components:
Component | Description |
<apex:form> | Creates an input form. |
<apex:inputField> | Adds an input field bound to a Salesforce field. |
<apex:commandButton> | Adds a button to perform actions (e.g., Save). |
<apex:datatable> | Displays data in a table format. |
<apex:chart> | Displays data in chart form. |
Calling Visualforce component in Page
- You can call a Visualforce component from a Visualforce page. In fact, this is one of the primary use cases for Visualforce components: they are reusable building blocks that can be included in multiple Visualforce pages.
Step 1: Create the Visualforce Component
Create a reusable component using the <apex:component>
tag. For example:
Visualforce Component (ComponentName: CustomGreeting
)
<apex:component>
<!-- Attribute that can be passed to this component -->
<apex:attribute name="username" type="String" description="Name of the user" />
<h1>Welcome, {!username}!</h1>
</apex:component>
Key Points:
Components can accept attributes using
<apex:attribute>
.In this example, the component expects a
username
string.
Step 2: Include the Component in a Visualforce Page
Call this component in a Visualforce page using the component’s name in the format:<c:ComponentName>
(where c
is the default namespace).
Visualforce Page (PageName: GreetingPage
)
<apex:page>
<c:CustomGreeting username="John Doe" />
</apex:page>
Key Points:
Use
<c:CustomGreeting>
to reference theCustomGreeting
component.Pass the
username
attribute to the component.
Step 3: (Optional) Pass Data Dynamically
You can pass dynamic values from a controller or other Visualforce elements.
Example with a Standard Controller
htmlCopy code<apex:page standardController="Account">
<c:CustomGreeting username="{!Account.Name}" />
</apex:page>
In this case, the username
is dynamically fetched from the Account Name.
Controller in Visualforce
In Visualforce, a controller is an Apex class that acts as the brains behind a page or component.
A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified in associated Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that should be displayed in a page, and can modify component behavior.
Types of Controllers:
Standard Controllers:
Automatically generated by Salesforce for standard objects.
Provide basic CRUD (Create, Read, Update, Delete) operations on a single record.
Limited customization options.
Custom Controllers:
Developer-defined Apex classes.
Offer full control over page behavior and data manipulation.
Can handle complex scenarios and integrations with other systems.
Example of Custom Controller:
- Visualforce Page
<apex:page controller="AccountController">
<apex:form>
<apex:pageBlock title="Account Details">
<apex:pageBlockSection>
<apex:inputField value="{!acc.Name}" />
<apex:inputField value="{!acc.Phone}" />
</apex:pageBlockSection>
</apex:pageBlock>
<apex:commandButton value="Save" action="{!save}" />
</apex:form>
</apex:page>
- AccountController Class
public class AccountController {
public Account acc { get; set; }
public AccountController() {
acc = [SELECT Id, Name, Phone FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')];
}
public PageReference save() {
update acc;
return null;
}
}
Variables in visualforce:
- Global Variables
Purpose: Used to store and access values across multiple components within a page.
Declaration: Defined using the
apex:variable
tag.
<apex:variable var="counter" value="0"/>
<apex:repeat value="{!myRecords}" var="record">
<apex:outputText value="{!counter} - {!record.Name}" />
<apex:variable var="counter" value="{!counter + 1}"/>
</apex:repeat>
- Formula Variables
Purpose: Used to calculate values based on expressions and store them for later use.
Declaration: Defined using the
apex:variable
tag with a formula expression.
<apex:variable var="totalPrice" value="{!product1.Price + product2.Price}"/>
<apex:outputText value="Total Price: {!totalPrice}"/>
- Conditional Expressions
Purpose: Used to control the visibility of elements based on conditions.
Declaration: Used within
apex:outputPanel
,apex:repeat
, or other tags using therendered
attribute.
<apex:outputPanel rendered="{!account.IsActive}">
<apex:outputText value="Account is Active"/>
</apex:outputPanel>
Connecting Visualforce with Apex:
- ViewAccounts.vf
<apex:page controller="AccountController">
<c:CreateAccountComponent/>
<apex:form>
<apex:pageBlock title="Account List">
<apex:pageBlockTable value="{!accounts}" var="account" id="accountTable">
<apex:column headerValue="Account Name">
<apex:outputText value="{!account.Name}"></apex:outputText>
</apex:column>
<apex:column headerValue="Phone">
<apex:outputText value="{!account.Phone}"></apex:outputText>
</apex:column>
<apex:column headerValue="Industry">
<apex:outputText value="{!account.Industry}"></apex:outputText>
</apex:column>
<apex:column headerValue="Action">
<apex:commandButton
value="Delete"
action="{!deleteAccount}"
reRender="accountTable">
<apex:param name="accountId" value="{!account.Id}" assignTo="{!accountId}"></apex:param>
</apex:commandButton>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
- AccountController
public with sharing class AccountController {
public List<Account> accounts {get; set;}
public Id accountId {get; set;}
public AccountController() {
fetchAccounts();
}
public void fetchAccounts() {
accounts = [SELECT Id, Name, Phone, Industry FROM Account];
}
public void deleteAccount() {
try {
if (accountId != null) {
List<Account> accountsToBeDeleted = [SELECT Id FROM Account WHERE Id = :accountId];
delete accountsToBeDeleted;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Account Deleted Successfully'));
fetchAccounts();
} else {
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'No account ID provided.'));
}
} catch (Exception e) {
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Error deleting account: ' + e.getMessage()));
}
}
}