Thursday, May 15, 2014

Introduction to Visualforce

Introduction

The other day a friend came across my blog and asked me; what is this Visualforce and Apex thing you are blogging about anyway?

Good question I thought. She probably still wouldn’t understand this post, but at least one would expect a blog with the title „Apex & Visualforce 101“ to begin with a short introduction to Apex and Visualforce. My bad. This post gives a brief introduction to Visualforce, what it is, why you should use it, when to use it and how to use it. A separate Post will tackle an introduction to Apex.

What is Visualforce?

Once upon a time, in a far far away kingdom, only traditional Web technologies like HTML (HyperText Markup Language), CSS (Cascaded Style Sheets), JavaScript, Flash etc. were used to develop views. 
A View can be defined as a representation of the information you wish to display to your users. This would most likely be the information that users will see on their browsers when they visit your website or use an application you have developed on the Force.com platform. So what has all this got to do with Visualforce? Read on!

With the need to build more powerful Views more quickly, came the realization that HTML was pretty limiting. HTML is tag-based, meaning it offers a bunch of tags which can be used to represent different types of information in different ways. But these tags offer only the very basic functionality you would need. To be fair, there are still quite a number of sites out there written purely in HTML but the amount of code, time and effort required to build and maintain such a site or application would be monstrous. 
Just like HTML, Visualforce is a tag-based programming construct that is used to build views. But it is much more powerful, because it has a larger number of tags that group common functionality together and it has been designed to optimally work with the Salesforce.com and the Force.com platform. What this means is, the way Visualforce interacts with the business logic layer which provides the information to display on the view, handles navigation, user input, communication with other systems code, asynchronous(AJAX) possibilities etc. have all been optimized to run in the most efficient way possible using Visualforce

Another web programming paradigm that can be used to understand what Visualforce is and its role in the whole development process of an application is the Model-Viel-Controller or simply MVC pattern.

Model-View-Controller (MVC)

MVC as the name says is made up of the Model, the View and the Controller.



Model


This is also sometimes called the data layer. It refers to the data on which your application will be built. If you were constructing a house, you could think of this as the foundation on which everything else will be built. The data that makes up this layer will most often reside in a database. On the Force.com platform, this layer consists of all standard and custom objects, their fields and the relationships between them.

View


This is the presentation layer and is used to display or gather information to the end user of your application. Visualforce pages constitute one of the main implementations of this layer. In Salesforce other Views include, Visualforce components,  page layouts and tabs.

Controller


This is the business logic layer. It is used to connect the Model to the View. It does this by getting the dataset required by the View from the Model, updating the dataset on the Model when the View changes, performing other business related task like sending emails, performing validations, page navigation etc. In Salesforce this business logic layer consist of Visualforce Controllers, Apex Classes and Triggers, Workflow Rules etc.

The main advantage of using the MVC pattern is that it leads to an effective utilization of resources by simplifying division of labour during the software development process. Different teams can concentrate on developing different layers of the application.

Visualforce fits nicely into the MVC pattern and is used to develop the View which constitutes what the user sees and ways he can interact with or consume what he see.


Why you should use Visualforce


Visualforce is a powerful tool for developing User Interfaces on the Force.com platform. Below are the most important advantages offered by this powerful GUI (Graphical User Interface) programming paradigm;

  • Performance: if there is only one reason why you should use Visualforce, then this is it. Visualforce is designed to display with the same performance as standard pages. The reason for this is, Visualforce is compiled on the server and therefore not tied to the limitations of your browser. 
  • Visualforce offers many tags out of the box which you can used to build pages with or without the look and feel of the standard pages. These range from tags for building tables, charts, to tags for use with chatter, live agent, Visual Workflow etc. Adding a related list to you page is as simple as using the related list tag and specifying which related list to add. You can link specific page elements to your data such that these fields respect all validation rules, data types etc. You can pull in the chatter feed for a record with these tags and let users follow records directly from your Visualforce page. These tags always begin with the “apex” keyword such as in the example below
  <apex:outputText value="{!account.Name}" styleClass="companyName"/>  


         Please click here to view the complete reference of the powerful tags offered by Visualforce.
  • Visualforce is extensible. If the Visualforce component reference does not have what you want, you can build your own component. Sometimes you simply want to build a reusable component that you can use in several different pages. This components can then be added to your page like this;
 <c:OpportunityPopup />  

         In this example, OpportunityPopup represents the component name.

         You could also define and register your own namespace unique to your company, data,                   process etc; and then use this to reference your components.

 <projectJubilee:CustomerBadgeInfo />  
         
         CustomerBadgeInfo would be your component which you could access using your unique              namespace projectJubilee.
  •  One of the most important reasons why Visualforce could be useful for your application is that it gives you the possibility of displaying information or data from systems external to your current salesforce implementation. Due to governor limits and the fact that some business cases don’t allow data to be in Salesforce, may be for legal reasons, or the fact that it is needed just by a very small subset of users, it doesn’t always make sense to add your data to Salesforce. Instead you will have the data in an external system and retrieve it using the Web Services API or outbound callouts and display the information when it is needed on a Visualforce page.
  • Visualforce can be used effortlessly and seamlessly with all common web technologies such as HTML, JavaScript, CSS, Flash and Flex. This is because at run time when you author your page and hit save, the Visualforce tags on your page are parsed on the server and an HTML page is returned and displayed. Right-click on your browser and click “view page source” to verify this. For this reason you can combine the best of Visualforce with the best of other technologies to provide your users with even more powerful and interactive applications.

Initial Steps


There are a couple of ways to author your Visualforce pages. Before you begin, it is important to identify how you will like to create and edit Visualforce pages. I will mention three important once here. These are;
  • Development Mode
  • Developer Console
  • Eclipse

Development mode


To begin, you will have to check the box for Development Mode on your user profile if you intend to create web pages directly from the browser. To create an Apex Page, simply go to the browser, clear everything after “.com” and append “/apex/nameOfYourPage” and press enter. An error message will display showing the the page does not exist yet and you will be give the posibility to create the page right from your browser



Then click on “Create Page nameOfYourPage” to create your Visualforce page. You will notice that your screen is divided into two. In the second half of the screen, you will be able to write your Visualforce code. The main advantage of using this method is, whenever you make changes to your page and save,  you will immediately see the changes in the section of the page above. You also have a link to the  complete Visualforce component reference on the right side of the screen just above the development area.

Developer Console


If you intend to do more than create Visualforce pages, it might be preferable to use the Developer Console. What I mean by more is, if you will also be creating Apex Classes which is very likely since you might be creating Controllers as well, running Apex test classes, checking Apex code coverage and covered code segments, executing SOQL Queries, checking debug logs etc. The Developer Console offers you all these possibilities and much more.


To access the Developer Console, click on your name at the top right side of the platform and then on Developer Console.

Force.com IDE (Eclipse)


Salesforce offers a plugin, the Force.com plugin for Eclipse IDE. This is my personal preference. Most of the things you can do with the Developer Console, can also be done in Force.com IDE. But Force.com IDE offers a bit more possibilities than the Developer Console. If you intend to do versioning as with SVN Subversion then use Eclipse with the Force.com IDE plugin. Do you want to be able to deploy between different environments or orgs? Then use the Force.com IDE. The Force.com IDE also has a Schema with which you can view the complete data Model for you org which can be very useful when you wish to find out the relationship between your objects.


Look here on installation instructions for the Force.com IDE.

Now that we know what Visualforce is, why to use and how to use it let us answer the question when  to use it.

When you should use visualforce


You should use visualforce when you require a custom look and feel with your application. The standard look and feel is pretty limited in most scenarios and you can’t alter it much. You can configure page layouts to add fields of different data types, add sections and related list, links and buttons, but that is it more or less it. With Visualforce the type of View you can build is not limited in anyway.
You may want to build customised pages the retain the look and feel of standard pages or you may want to build customised pages and apply you own styles. Combining the power of Visualforce together with Force.com Sites you can build powerful Web applications that do not look anything like the Salesforce platform. Just by setting a single attribute you can disabled all Salesforce style sheets and apply yours.

So use Visualforce whenever you need a customised view with or without the look and feel of Saleforce.com platform, maybe to pull together information from different objects on to a single view, pull information from external sources onto you views, mash up your views with applications from external sources e.g. Google Maps, build powerful web pages together with Force.com Sites etc. 

The possibilities and indeed amazing.

How to use Visualforce


Visualforce can be used in the following main ways;

  • Links: You can have custom links open up your Visualforce pages when clicked. A use case could be to pull data from an external source and display it to the user.
  • Standard buttons: Visualforce pages could be built to replace the standard detail and edit salesforce pages. The standard “New” and “View” buttons can then be configured to use these Visualforce page.
  • Custom buttons: Custom buttons could be created and attached to specific Visualforce pages. The page layout could then be customised and the custom button added to the page. Clicking on the button opens the Visualforce page
  • Custom Tabs: Visualforce pages could be created and then tabs created for these pages. Users can then add the tabs to applications as they would any standard tab. This tab then gives access to the Visualforce page.
  • Visualforces pages could also be embedded within standard page layouts. This would be done, by creating a Visualforce page and then customize a standard page layout and adding this Visualforce page to it, usually in a section of its own. A common use case I have seen very often of this is adding a map to a standard page layout
  • You can use Visualforce to build pages for your Force.com Site. You could then either expose information and data to your users or to the general public e.g. product information which could be viewed by everyone.

Controllers


A discussion on Visualforce without mention controllers is like talking about floating houses. You will not see them very often except you are in a Disney movie called Up. Visualforce Controllers or simply Controllers play a major role when building Visualforce pages. This is because they hold all the business logic required to retrieve and make datasets available to the page and validate and update this dataset so it can be persistent to the model or data layer when need. Controllers are not limited to performing data manipulation task (DML operations). Controllers can be used to control navigation, perform all sorts of validation, send emails, upload files from the user’s computer to Salesforce or Systems external to Salesforce (such as Google cloud, Dropbox etc), perform outbound callouts, Web services etc.

Note however that although most Visualforce pages you will come across will have a controller, not all Visualforce pages require one. An example of a Visualforce page that may not require a controller is one that embeds a Visual Workflow in the page which doesn't depend on data from any object in the system. This is mostly the case with Visual Workflow built to gather surveys or perform some sort of assessment. The standard guest user profile which is created whenever a Force.com site is created can then be configured to store the survey response on a custom object in Salesforce.

There are two types of controllers; standard and custom controllers. Controller extensions can be used to extend both standard and custom controllers.

Standard Controllers


Every object in Salesforce, be it a standard or custom object has a standard controller which is responsible for the functionality used on the standard pages such as editing and saving a record. To define a standard controller, we use the StandardController as follows

 <apex:page StandardController="Opportunity" sidebar="false" title="Opportunity Report">  
      <h1>THIS IS A DRAFT OPPORTUNITY REPORT FOR TEST PURPOSES</h1>  
 </apex:page>  

The StandardController attribute takes the name of the object whose Controller it will use. The standard methods of this controller such as the save method are now available for use within the page and will behave exactly as if the user were on a standard Salesforce page.
If the user intends to add a bit more control to the way the data should be presented or wants to control the navigation within the page, he will normally add a controller extension to the already existing controller.

Controller Extensions.


Controller Extensions are added with the attribute “extensions”. As the name says, they are used to extend the functionality of the controller already present within the page, be it a standard or custom controller. But it is more common to use them with standard controllers.

 <apex:page standardController="Account" recordSetVar="accounts" extensions="AccountPagination">  
 </apex:Page>  

Several extensions can be added to a single page. Take not that only overridden methods in the first controller will be called. This is often a pitfall for many people so beware; else you might spend hours searching for a bug where there is none.
The constructor of the extension muss have an argument which initializes the controller which it is extending. Using this controller, the extension can then have access to the record which will be displayed on the page as shown here;

 public OpportunityEmailOnClosedCtr(Apexpages.StandardController stdController){  
       stdController.addFields(new List<String>{'StageName', 'Email_Recipients__c', 'TrackingNumber__c', 'Email_Content__c'});  
       this.opportunity = (Opportunity)stdController.getRecord();  
 }  

One thing worth mentioning here is the “addFields” method in the controller above. For optimization purposes, Salesforce always only returns the fields that are queried. For this same reason it is not possible to do something in SOQL (Salesforce Query Language) like “SELECT * FROM Account”. You always have to explicitly query what you want. So if you do not use a field on the Visualforce page, the record fetched in the constructor will not contain any values for this field. However you might want to use this field in the controller extension. Before people used to add hidden fields to the page to obtain values for these fields in the record. This introduces security issues to your page and might make your page unnecessarily bulky (always think about View State and  governor limits). Instead use the “addFields” method and specify what additional fields you need. How great is this.

Custom Controllers


These types of controllers are used when we want complete control over the way our page is going to behave. We might want to create, update and delete related records or customize navigation to and from other pages. We will normally use custom controllers for these situations where we require heavy customisations on our page and the dataset we want to display to the user. For example, you might need to wrap your data in some sort of a wrapper object so as to add more functionality to your data which may not need to be persisted e.g adding checkboxes to your data to let users select particular records.
Custom controllers are defined user the “controller” attribute

 <apex:page controller="PositionController" recordSetVar="positions" sidebar="false" showHeader="false">  
 </apex:page>  

Custom controllers have a no argument constructor. If you however need to perform some initialisations when your Visualforce page is loaded, write an init method and use the “action” attribute of the page definition to call your init function

 <apex:page standardController="Test_Centers__c" extensions="Test_Center_Controller" action="{!Init}" Sidebar="false">  
 </apex:page>  

Finally, take note that you are not allowed to perform any DML operations in the constructor of your controllers.

Datasets, Data Bindings (Properties) & Action Bindings


After this brief introduction on controllers it will be very useful to mention the concept of getters and setters and bindings.

Anyone who has ever worked with Java Beans before is very familiar with the less code, more work approach using the concept of properties with public getters and setters. This same concept is used in Visualforce Controllers, the only difference being that the properties are something halfway between a variable and a getter or setter.

 public List<TeamMembers> OpportunityTeam { get; set; }  
 public String chosenFiscalYear{get; set;}  
 public String chosenRegion {get; set;}  

These getter and setter properties are used to present and maintain the dataset from the data layer to the page. These properties make sure that the dataset is always consistent at all times so that the same data seen by the page is the same data on the controller.
Normally when the Visualforce page loads, the getter properties are called and they present the page with the data it needs. If the user changes a value on the page and hits a button tied to an action such as “save”, the setter for that value is first called and the value is updated. The “save” action is then called. When the action is called, the value is already updated. Very important! So very important to remember, all getters are called when the page is loaded and setters are always called before the action functions run.
It is this functioning of the getter and setter property that we refer to as data binding. Data binding keeps the dataset consistent between the controller and the view.
Action binding is the binding of specific action methods to elements in the view. Action methods could be bound to a button, a link, an actionFunction etc.

 <apex:actionFunction name="retrieveSearchedSession" action="{!retrieveSearchedSession}" oncomplete="HideEventChatterFeed(); setSessionSearchTitle('{!searchTerm}'); hideBlockUI();" rerender="recordCounter">  
      <apex:param assignTo="{!searchSessionId}" name="searchSessionId" value=""/>  
      <apex:param assignTo="{!searchTerm}" name="searchTerm" value=""/>  
 </apex:actionFunction>  

In the example above, the action method retrieveSearchedSession after the setters for the properties searchSessionId and searchTerm have been called to update these values in the dataset. The retrieveSearchedSession  action can then use these values to perform the SOSL (Salesforce Object Search Language) query and update the dataset with the required records.

Other Important Visualforce concepts


To conclude this discussion on Visualforce pages, we will introduce a few key concepts that you should always keep in mind when building Visualforce pages.

View State and Transient Variables

As mentioned above data binding uses properties to maintain a consistent dataset between the controller and the Visualforce page. The Visualforce page is however just HTML code and as we all know HTML is stateless. So how is a consistent state of the dataset maintained between the Visualforce page and the controller? The answer is View State. The View State contains all properties required to maintain state between the page and the controller. This View State is passed back and forth between the page and the controller whenever they communicate with each other.
For this reason it is very important to keep the size of the View State as small as possible. One on the main ways to do this is to use the transient keyword on variables or properties that will not be added to the View State. We mentioned the controllers ‘addFields” method above to add fields not accessed in the page but needed in the controller. If you define properties to hold values from these fields, such properties would be good candidates to be decorated with the transient keyword.
Always think about what you are doing properly. This will make you more efficient as you will avoid common pitfalls from the onset

Limits


The size of each Visualforce page is limied to 15 MB. This should be more than enough for most Views you will need to create. If you find yourself hitting this limit, then you are doing something seriously wrong. One very important limit is the 135 KB size of the View State. 

System mode vs user mode


While standard pages and pages utilizing only the standard controller operate in user mode, meaning all profile based permission sets and sharing rules are respected, custom controllers and controller extensions operate in system mode, meaning profile based permission sets and sharing are not respected. So always remember to add the “with sharing” to your custom controller or controller extension definition if you want profile based permissions and sharing to apply on your Visualforce page.

Dynamic Visualforce


There are times when you might need to customize the View to show information based on the profiles of the users or on a combination of values from different records. In these cases, the “rendered” attribute used to show and hide sections of the page might just not cut it anymore or might even just result in more complexity. In such cases you should consider using dynamic Visualforce. In this case the Visualforce mark-up is built in the controller and sent to the page to be dispayed. Salesforce however stresses the fact that, this is not the main way Visualforce is meant to be used. I stress this point too.

Conclusion

Having been using Visualforce for a while now, I can say; at times it blows my mind how easy it is to create stunning web applications using Visualforce. Anyone who has done traditional web development (without the aid of constructs like Visualforce, JSP, JSF) will very much appreciate the possibilities you have with Visualforce and how much time and effort it saves you. I hope from this article you were able to get a feeling of the possibilities you have with Visualforce. Leave a comment that might help others looking at this post in the future. Thanks for reading

3 comments:

  1. Wow wow wow!!!! This is Excellent Viban.WELL DONE !!!!!

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete