Introduction to Visualforce

Visualforce is the framework in Salesforce CRM that allows you to further customize your organization's user interface beyond the standard functionality that we have previously covered.

As described previously, using Visualforce, you can combine data from multiple objects, create mash-ups with data from external web services, and even override some of the logic and the behavior found within standard Salesforce CRM application functions. Visualforce consists of the following three elements:

  • Visualforce pages: These are used to define the user interface
  • Visualforce components: These can be thought of as a library of standard or custom-built sections of Visualforce code
  • Visualforce page controllers: These are used to control the behavior of Visualforce pages, and can either be controlled by standard logic, or you can create custom logic to change or extend the standard Salesforce CRM behavior

Visualforce pages

The Visualforce framework allows for the creation of Visualforce pages. These pages are a little like documents that are stored in Salesforce and are comprised of instructions that specify how the page is to appear and function. Similar in nature to HTML, Visualforce pages comprise of a tag-based markup language, with each Visualforce tag type corresponding to a particular user interface component.

Note

The maximum size of a Visualforce page cannot be greater than 15 MB.

For the more technical readers, Visualforce performs similar functions such as, say, Java Server Pages (JSP) or Active Server Pages(ASP), and is used to manage the retrieval of the data from the Salesforce platform and the rendering of results via the Internet browser user interface.

Creating a Visualforce page

Now that you are aware of the basic building blocks provided by Visualforce, we will describe the creation of Visualforce pages. This section looks at how the creation and modification of pages can be done and shows you the following two ways of doing that:

  • Using the Visualforce pages setup page
  • Using the development mode

Visualforce pages setup page

To go to the setup page to create Visualforce pages, navigate to Setup | Develop | Pages. Now, click on the New button to create a new Visualforce page. Select an existing entry to view the page, or click on Edit to modify it, as shown in the following screenshot:

Visualforce pages setup page

The Visualforce development mode

We can also use something called the Visualforce development mode to create and edit Visualforce pages initially. This can be a better choice because it provides several useful features that make it easier to build Visualforce pages.

To start using the development mode, you need to activate it on your user record by navigating to Your Name | My Settings | Personal | Advanced User Details. Now, click on the Edit button, select the Development Mode checkbox (as shown in the following screenshot), and then finally, click on Save.

The Visualforce development mode

When in the Visualforce development mode, you can create a new page simply by entering a unique URL into the browser's address bar.

Automatic creation of new Visualforce pages

By entering a unique URL(for a Visualforce page that does not exist) into the browser's address bar, a new page called will be created. For example, typing the URL https://na10.salesforce.com/apex/GoogleMap will enable a new page called GoogleMap to be created.

You need to be careful about entering the correct URL text, as it is the /apex/GoogleMap part in the preceding example that prompts Salesforce CRM to check and create the new page if it does not currently exist. It is also important that the start of the URL be entered correctly. The https://na10.salesforce.com part refers to the Salesforce instance for your Salesforce CRM application.

When entered correctly, the following screenshot, which allows you to create the Visualforce page, will be presented:

Automatic creation of new Visualforce pages

This, as you can see, can save a lot of time when creating a lot of pages, as you do not need to keep navigating to the setup sidebar section, and it saves a number of mouse clicks. The resulting edit page, when you click on the Create Page GoogleMap link, is the same edit page as the one accessed through the setup route, as shown in the following screenshot:

Automatic creation of new Visualforce pages

When the development mode is enabled, a development section is automatically presented below the Visualforce page that you are creating or editing, which displays an editor section. To show or hide the development section, click on the following icon:

Automatic creation of new Visualforce pages

The editor allows you to write Visualforce component tags directly within the browser window and also offers the following features:

Automatic creation of new Visualforce pages

As shown, the seven menu functions are provided for the following:

  • Saving the page
  • Searching for text
  • Navigating to a specified line in the code
  • Undoing changes
  • Redoing changes
  • Increasing the font size of the text
  • Decreasing the font size of the text

Clicking on the Component Reference link will navigate to the online documentation, which provides descriptions as well as example code for all the Visualforce components, as shown in the following screenshot:

Automatic creation of new Visualforce pages

In addition, the page editor also provides highlighting and an autocomplete feature that automatically displays available component markup tags, as shown in the following screenshot:

Automatic creation of new Visualforce pages

The greatest benefit of having the development mode enabled when building Visualforce pages using the Salesforce CRM platform is that as you add component tags and build up the code in the page, you can click on the save icon and view the resulting changes immediately.

Note

The Visualforce page must be free from errors before the page is allowed to be saved.

Visualforce components

We have seen in the previous section that Salesforce provides a set of standard, prebuilt components, such as <apex:actionFunction> and <apex:actionStatus>, which can be added to Visualforce pages to construct pages of functionality. In addition, you can build your own custom components to augment this library of components.

Similar to the way functions work in a programming language, a custom Visualforce component allows you to construct common code and then reuse that code in one or more Visualforce pages.

Custom components allow you to define attributes that can be passed in to each component. The value of an attribute can then change the way the markup is displayed on the final page and the controller-based logic that executes for that instance of the component.

Visualforce custom components consist of Visualforce markup tags using the standard <apex:component> tag, and therefore, rather than repeating the Visualforce markup required for every page that you need the common code on, you can define a custom component that has certain attributes and that uses these attributes to display the functionality on the page. Once defined, every Visualforce page in your organization can leverage the custom component in the same way as a page can leverage standard components, such as <apex:dataTable> or <apex:actionStatus>.

Creating an example mash-up with Visualforce

To construct our example mash-up, we will follow these steps:

  1. Delete the default new Visualforce markup content.
  2. Change the Visualforce Controller to specify an Account Standard Controller.
  3. Copy and paste the Google map code and add Salesforce-specific merge fields

Deleting the default new Visualforce markup content

Delete the existing Visualforce page text (lines 2 to 5 in the following screenshot) and leave just the starting and ending tags, which are <apex:page> and </apex:page>, as shown in the following screenshot:

Deleting the default new Visualforce markup content

Changing the Visualforce Controller to specify an Account Standard Controller

We also need to change the Visualforce page controller so that we can read the value of the fields stored on the Account record. Controllers will be looked at in more detail later in this chapter, but for the moment, we will change the opening tag, which is <apex:page>, and add the standardController attribute, which allows the call to the Account record, as shown using the <apex:page standardController="account"> code:

Changing the Visualforce Controller to specify an Account Standard Controller

Copy and paste the Google map code and add Salesforce-specific merge fields

We will copy and paste the following code, which contains Salesforce merge fields, to render a Google map on our account records:

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
  var map;
  var mapOptions = {
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControl: false
  }
  var mapMarker;
  var geocoder = new google.maps.Geocoder();
  var address = "{!SUBSTITUTE(JSENCODE(Account.BillingStreet),'
',' ')}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalCode}, " + "{!Account.BillingCountry}";
  geocoder.geocode( {address: address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK && results.length) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
        map = new google.maps.Map(document.getElementById("map"), mapOptions);
        map.setCenter(results[0].geometry.location);
        mapMarker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: "{!Account.Name} " + address
        });
      }
    } else     
        document.getElementById("map").innerHTML = "Unable to find or display a map for {!Account.Name}'s billing address : " + address;
  });
}
</script>
<div id="map" style="width:100%;height:300px"></div>
<script>
    initialize();
</script>

We use Salesforce merge fields for the Account record to pass the billing address data to the Google map API as shown in the following snippet:

  var address = "{!SUBSTITUTE(JSENCODE(Account.BillingStreet),'
',' ')}, " + "{!Account.BillingCity}, " + "{!Account.BillingPostalCode}, " + "{!Account.BillingCountry}";

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

The final code will appear within the Visualforce page, as shown in the following screenshot:

Copy and paste the Google map code and add Salesforce-specific merge fields

When saving the Visualforce page, the page is rendered immediately; however, at this point, there is no billing address data to be passed to the Google map widget (this will be rendered properly after we have added the Visualforce page to the Account Page Layout) and therefore, an error will initially be presented, as shown in the following screenshot:

Copy and paste the Google map code and add Salesforce-specific merge fields

Note

Notice how with the use of the <apex:page standardController="account"> tag, the Accounts tab is now automatically highlighted.

Adding the Visualforce page to the Account page layout

Now that we have completed and saved the Visualforce page, we can add the GoogleMap page to the Account page layout. To add Visualforce pages to Accounts, navigate to Setup | Customize | Accounts | Page Layouts. Now, select the appropriate page layout. Here, we are going to add it to the page layout called Account Layout by carrying out the steps discussed in the upcoming section.

Adding a new section to the Account page layout

The new section has been given the title Google Map and has been set to 1-Column width and positioned by dragging-and-dropping it below the Account System and Description Information section, as shown in the following screenshot:

Adding a new section to the Account page layout

Adding the Visualforce page to the new page layout section

Now, drag-and-drop the GoogleMap Visualforce page to the Google Map section on the page layout, as shown in the following screenshot:

Adding the Visualforce page to the new page layout section

Click on Save; we are now ready to test by navigating to an account page.

Running the completed Visualforce page

Navigate to the Account tab and select an existing account to verify that the mash-up is working as expected.

Note

You will need to ensure that a billing address is completed for the account record. The Billing Address composite field is a standard Account field in Salesforce CRM.

Here, we have an existing account for Salesforce.com with the Billing Address field populated, which displays a Google map when the account detail page is loaded, as shown in the following screenshot:

Running the completed Visualforce page

Tip

How do I suppress browser security warnings in Internet Explorer?

By default, Internet Explorer displays this security warning message when a page contains a mixture of secure (HTTPS) and nonsecure (HTTP) content: This page contains both secure and nonsecure items. Do you want to display the nonsecure items?.

When you create a mash-up with a nonsecure URL, users might see this warning message depending on their browser security settings. To suppress this warning in Internet Explorer, follow these steps: from the Internet Explorer tools menu, select Internet Options, click on the Security tab, and click on the Custom Level button, and finally, in the miscellaneous section, set Display mixed content to Enable, as shown in the following screenshot:

Running the completed Visualforce page

Visualforce page controllers

As described earlier in this chapter, there are four types of controllers that can be used to control the functionality behind a Visualforce page.

Standard controllers

A standard controller provides access to standard Salesforce CRM behavior, and as shown in our client-side mash-up example, they can be specified using the following tag and attribute as the first line in the Visualforce page:

<apex:page standardController="Account">

Standard controllers are available for standard objects, such as Account, Contact, and Opportunity, as well as for custom objects and provide access to standard Salesforce CRM data operations and behavior for actions such as save, edit, and delete.

Custom controllers

Custom controllers are used for fully customized behavior and are implemented using the Visualforce tag and attribute as follows:

<apex:page controller="CustomAccount">

Controller extensions

Controller extensions are used to extend the behavior of standard controllers and allow the addition of customized functionality. Controller extensions are provided using the Visualforce tag and attribute as follows:

<apex:page standardController="Account" extensions="CustomAccountExtension">

Standard list controllers

Salesforce record pages allow users to filter the records displayed on the page using list views (covered in Chapter 3, Configuration in Salesforce CRM). For example, on the accounts home page, users can choose to view a list of only the accounts they own by selecting My Accounts from the list view dropdown.

Standard list controllers provide the same list view picklist and are implemented using the following tag and attribute as the first line on the Visualforce page:

<apex:page standardController="Account" recordSetVar="accounts">

Apex code

The Apex code language in Salesforce CRM is based on Java, which is one of the most popular programming languages for Internet and web-based applications, and is executed on the Salesforce platform servers.

Although based on Java, the Apex code and the Salesforce CRM platform is not a general-purpose computing platform that can be used to run any type of program that developers might choose to run. Instead, Apex is kept intentionally controlled and limited and is, therefore, designed with the needs of the business and platform in mind.

Note

Apex code in Salesforce is not intended to solve every programming problem and is concerned principally to help developers gain advantages in development time, code conciseness, and reduction in maintenance costs.

Apex is used in Salesforce CRM to develop the code within Custom controllers and Controller extensions as well as Apex triggers, which we will look at shortly.

Apex is specifically designed to build business applications that manage data and services, and the language provides a highly productive approach to create applications and business logic. Developers can focus on the functionality required to solve the business problem and domain and need not be concerned with building the infrastructures such as database connection and error handling, which is managed by the platform.

It should be noted that as the Salesforce CRM platform is a multitenant platform, there are certain limits as to what and how much processing can be performed within certain operations. Such limits are known as Governor Limits, and there are some restrictions and requirements; for example, Apex code must be developed in a developer or sandbox organization and must have test methods to verify each line of code, and only then is it allowed to be deployed to production.

Note

For successful deployment to production, Apex code must have associated unit test methods that provide at least 75 percent successful code coverage.

Apex triggers

Apex triggers are blocks of Apex code that are executed before and/or after any record action, such as create, update, or delete, in the Salesforce CRM application.

Triggers are very powerful and can include complex code to control your process. They are used for complex business logic automation and where such functionality is too complicated to be implemented using validation rules or workflow rules, such as field updates. The development of Apex triggers usually requires the resource of a software developer, as they have certain restrictions and implications for the overall system.

When using multiple triggers, and alongside any existing workflow field updates, there needs to be a thorough understanding of any dependencies to avoid any ripple effect when records are created or updated. As trigger code can make changes to the record being updated within its own operation, any likely recursion effect needs to be understood and avoided.

Note

Apex triggers offer many benefits to an organization but also introduce some risks, as there needs to be awareness about certain patterns and limits (bulkifying triggers, governors, and so on.) imposed by the underlying platform.

It is particularly important to understand the timing, order of execution, and dependencies of the various rules and triggers within an organization.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.187.62