Visualforce is a framework that helps us to build custom user interfaces(UI) or custom pages. These pages are known as Visualforce pages. Visualforce pages similar to HTML pages are web pages but are specifically designed to be hosted on the Salesforce platform only.
Visualforce pages in Salesforce
Visualforce pages are created using a unique tag-based Mark-up language also similar to HTML. Therefore, the Visualforce framework includes the markup tags (for the UI) and server-side controllers (for providing logic) to build custom pages as per the requirement.
Visualforce pages are used basically for the scenarios which can not be fulfilled by the declarative approach.
- Display records from multiple Salesforce objects
- Edit multiple records at the same time
- override a salesforce button or tab ( Goto buttons and links and edit that from standard to Visualforce page)
- Show advanced charts using Javascript.
- Create a customized dashboard
- Embed a custom Visualforce page on the record detail page.
Creating Visualforce pages
Visualforce page can be created via Dev Console as well as within Pages under Quick find. We can also enable Development Mode and View state in development mode for the latter by enabling it under my settings > personal >user details.
The URL format of the Visualforce be like mydomain.visual.force.com/apex/vfpagename
We can use the same URL to click and create the visual page if not present.
Why are visualforce pages served from a different domain?
To improve security standards and block cross-site scripting.
Visualforce Page Architecture
Components of Visualforce page
- Visualforce page markup:
Under the parent markup <apex:page> we can use various scripting markups from HTML, Javascript, CSS, etc. - Visualforce page Controller
Visualforce page Controller and its types
A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components like the buttons on the visual force page.
1. Standard Controller in Visualforce page
Each object whether standard or custom object provides a standard controller and thereby can be bind to a Visualforce page component with the “standardController” attribute with their respective API names, e.g.
<apex:page standardController=”ObjectName”>
The standard controller respects the security model and runs with user permissions.
To further access the related data fields and functionality of that object,, use the Component Reference. A few common and worth mentioning pointers are as below:
- <apex: input field> associates with the existing object fields and respects their attributes (inside page block ) such as require, unique, etc as specified on the object detail page. We specify a value here with the field name we want it to render. We can also specify the label here, or we can put the tag inside PageBlock and PageBlockSection to dynamically dynamically fetch the object field label. A pageBlock is an area of the page that uses the styling similar to that of a Salesforce detail page but no default content.
- Accessing the field attributes with standard controller: value=”{!Account.Name}”
- !Account.Name binds to the Account Name field on the server side controller
- Referencing syntax : {!objectName.FieldName} or {!ChildobjectName.ParentObjectName.FieldName} –(upto 5 levels) or {!parentobjectName.ChildObjectName}—(one level).
- While an <apex:input> is a general-purpose input component. Also we can use <apex:inputText> when we define the field from scratch. Similarly, we have <apex:outputField> to fetch and display data from the database object or custom class. Under a pageBlockSection, it auto fetches the labels of the fields as well.
- Any interactions with the server must be bound under <apex: form>. We create pageBlock and PageBlockSection which take care of styling and label names specified by the same object that provides the controller. Under PageBlockSection which is a 2-row space, we can also specify PageBlockSectionItem that takes 1 row. We can override it by specifying the tabStyle alongside the controller specification to copy the style of another object.
- We can invoke actions like Save, Quick Save, Edit, View, Delete, Cancel, and List using CommandButton, CommanLink, ActionSupport, etc on a standard controller. Note that we use the exclamation mark (!) to bind the attribute. Binding here simply means connecting the attribute on visual force with its respective associate in the server-side controller. We can also choose to group the buttons using <apex: PageBlockButtons> and use other attributes like the location of the buttons, language, etc.
<apex : commandButton value=”Save” action=”{!Save}”/>
!Save binds to the specific save function on the controller side.
2. Custom Controller in Visualforce page
When we do not want to use the standard logic and functionalities defined by the salesforce objects and rather want to create our own custom logic, we use Custom Controller. We can override standard functions, create new functions and buttons, define different navigations to different pages with the click of a button. Custom Controllers are just Apex classes, used to define the logic of our visual force page without leveraging any object or a standard controller.
As the Apex class runs in System Mode, thereby the visual force components created using these custom controllers also run in system mode and are not governed by the security model unless specified with the “with sharing” keyword. Hereby to make it accessible in User Mode, we can use the “with sharing” keyword.
The custom controller apex class must have a non parameterized constructor as a custom controller can not have a constructor with parameters.
- As there ain’t any defined fields in custom controller opposed to case of the standard controllers. We define the same using <apex:outputLabel value= “Account Name” for=”accNameId”/>—– defining the label
<apex:inputText id=”accNameId” value=”{!name}”/>———-defining the input box. - We can put the above inside a PageBlockSectionItem tag to put them together in a single column. In the same way, we can define different fields and can then bind them with the corresponding custom controller/apex class. On the apex controller side, these field values retrieved are handled internally with the getter and setter property once defined as:
Access specifier record-type name {get; set;} ——- using this format to define the variables on apex class internally takes care of getting the specific value as well as setting the same. - We also specify various methods in the Apex class to hold the functional logic and implementation of custom buttons using (specified under action = “{!search}”attribute) we create on the visual force page. For example, a search operation can be defined as below in the Apex class
public pagereference search(){
string searchString = ‘%’+name+’%’;
accounts = [SELECT ID,NAME,TYPE,RATING FROM ACCOUNT WHERE NAME Like :searchString ];
return null; ———-does nothing but refresh or reload the page when used under pagereference (record-type) - We can choose to display the data using pageBlockTable in our Visualforce page by iterating over the list of data and displaying information about one object per row. A pageBlockTable table can always be with pageBlock tags. We can enable or disable the view of the by using pageBlockSection Rendered= True(Visible)/False. We can explore more attributes of page block like “Mode” that define the data pages’ look.
3. Controller Extension in Visualforce page
As the name suggests, to extend the functionality of a standard or custom controller we use the controller extensions. The standard controller runs completely in User mode while the custom controller in system mode. We can build a Visualforce page that respects user permissions.
Although a controller extension class executes in system mode, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which permissions, field-level security, and sharing rules of the current user apply. We can also leverage the built-in functionality of a standard controller and choose to override one or more actions and even add new ones.
To extend :
<apex:page standardController=”ObjectName” extensions=”myExtendedClass”>
Boiler plate to create the Controller extension “myExtendedClass” :
public class myExtendedClass{
public myExtendedClass(ApexPages.StandardController controller) {
}}
Standard list controllers in Visualforce page
Standard list controllers allow you to display or act on a set of records on a Visualforce page. Existing Salesforce pages that work with a set of records are list pages, related lists, and mass action pages. Standard list controllers can be used with the following objects as below:
- Account
- Asset
- Campaign
- Case
- Contact
- Contract
- Idea
- Lead
- Opportunity
- Order
- Product2
- Solution
- User
- Custom objects
To create a standard list controller :
<apex:page standardController=”ObjectName” recordSetVar=”accounts”>
The list can be displayed using <apex:pageBlockTable> and specified with value and var attributes, column and headerValue, etc. We can choose to extend another class and refine the list with specific criteria, create pagination (Previous, Next, First, Last) with panelGrid, etc.
All these functionalities can be referenced here in the Apex Component Documentation. Feel free to bookmark this as it is surely going to save you from the hassle of syntactical errors.
Clustered Style Sheets or CSS for Visualforce in Salesforce
We can use a variety of methods to provide styling to our visual force pages: Using Salesforce styles: Using TabStyle attribute to associate the styling of a page to that of any other standard controller like Account, Contact, etc. Using LightningStyleSheets to provide the page the looks of a lightning component. We can also impart styling to each block and section using attributes like Style, StyleClass, bgcolor, border, width, padding their colors, etc. We can even set the standardStyleSheet to false and let display the view as an HTML page.
Extend these using custom stylesheets
Using custom style: Alike in HTML we can specify various tags like <div>, <p>,<h> and specify styling for the same using style attribute. We can use :
Inline CSS : specifying the styles inside the specific tags and blocks.
<h1 style=”text-align:center;font-size:40px;”> Inline CSS </h1>
<apex:outputlabel style=”color:red;font-size:20px;”> Visualforce markup to show inline css</apex:outputlabel>
Internal CSS (defining them in style tag for a specific ID, Class, or Tag and referencing to them)
<style>
#mydiv{ margin :20px; height:100px; width:150px; background-color:yellow;} —ID reference
.div1{margin :20px; height:100px; width:150px; background-color:yellow;} —Class reference
h1{margin :20px; height:100px; width:150px; background-color:yellow;} —Tag reference
</style>
Referening as below:
<div id=”mydiv”> ——————–mydiv id reference
<h2> this is h2 </h2>
</div>
<div class=”div1″>——————–div1 class reference
<apex:outputLabel styleClass=”myH1″ > this is div 1</apex:outputLabel>
</div>
<h1> this is h1 again </h1>——————-h1 tag reference
External CSS: referencing CSS outside of the Visualforce page using the static resource. The same CSS defined above within the style tag can be saved in notepad with .css extension and thereby be uploaded as a static resource file to the salesforce platform to be referenced externally. The file can be referenced to the pages as : <apex:stylesheet value=”{!$Resource.FileName}”/>
Using the LDS or Lightning design system to impart styling like those of Lightning components.
How can you style a vf page that is rendered as a pdf using apex: detail. Field names are wrapping and I would like them to appear on 1 line. Thanks!