Skip to main content

VisualForce Best Practices

Accessing component IDs

When we refer Visualforce components in JavaScript, the ID attribute plays a major role. Every Visualforce component has an ID attribute. The ID attribute must be specified to a particular component in order to refer to it in JavaScript and it is used to bind the two components together. When the page is rendered, this ID attribute is a part of DOM ID of the particular component. The ID attribute must be unique as well. The following best practices are applied for accessing component IDs:
  • Use the $Component global variable to simplify access. For an example, when we have an input field with id="inputOne" within a page block with id="blockOne", we can access the input field with the$Component.blockOne.inputOne expression.
  • No need to specify an ID for a component you want to access if it is an ancestor or sibling to the$Component variable in the Visualforce component's hierarchy.

Page block components

The <apex:pageBlockSectionItem> component can have only two child components. With the customer requirements and the developing requirements, there can be more than two child elements inside<apex:pageBlockSectionItem>. Using <apex:outputPanel> we can add more than two elements in<apex:pageBlockSectionItem> as follows:
<apex:pageBlock>
  <apex:pageBlockSection>
    <apex:pageBlockSectionItem>
      <apex:outputLabel value="LabelName"/> 
      <apex:outputPanel>
<!—We can add our extra child components here within the apex:outputPanel --> 
      </apex:outputPanel>
    </apex:pageBlockSectionItem>
  </apex:pageBlockSection>
</apex:pageBlock>

Controllers and controller extensions

When we are developing controllers and controller extensions that are associated to Visualforce pages, we need to adhere to the following best practices:
  • By using the with sharing keyword, we can enforce the sharing rules in controllers. Then the code will execute in the user mode instead of the system mode.
  • We must not depend on the setter method to be executed before the constructor.
  • We must not depend on the execution order or side effects while creating custom methods in a custom controller or a controller extension.
  • Do not use DML operations inside a loop.
  • While performing record filtering, add filters in the following order:
    • In SOQL
    • In Apex
    • In Visualforce
  • If possible, calculations must be performed in SOQL instead of Apex.

Improving Visualforce's performance

The performance of a Visualforce page is a key factor to consider in development because performance is a reason that effects the end user's satisfaction of the application. The following are the best practices to improve Visualforce's performance:
  • Use only one <apex:form> tag per Visualforce page because each <apex:form> tag adds a view state to the page. A Visualforce page has a limit for view state size that is 135 KB. We can decrease the loading time of a Visualforce page by reducing the view state size.
  • Try to use the transient keyword in custom controller as much as possible. The state is not maintained for transient instance variables. If a particular instance is used only in the page request, then it must not be a part of view state. It will help to reduce the view state size.
  • When using an SOQL query to refer data of a particular object, use only the relevant data in the SOQL query.
  • When designing the Visualforce page, do not overload the page with excessive functionality and more data. Overloaded pages will increase the view state, page size, heap size, and risk hitting the governor limits for the view state.
  • To decrease the loading time of a Visualforce page:
    • Do not use SOQL queries in getter methods
    • Frequently-used or global data must be cached
    • Reduce the number of records displayed in the page by using the built-in pagination ofstandardSetControllers or limiting the data in SOQL queries
  • We can increase the time interval for calling the Apex controller by using the <apex:actionPoller>component to reduce the delays in multiple concurrent requests.
  • Use the SOQL OFFSET to implement the pagination of a specific subset of results within SOQL.
  • If we have large quantities of read-only data in an organization, then we must use a custom object or custom setting to store that data.
  • Use <apex:repeat> to iterate over large collections.
  • Do not hardcode pick list values in the Visualforce page, and use the controller to add them to aselectOption list.
  • Use the lazy loading approach to reduce or delay the loading of data according to the essentiality. In lazy loading, the essential features will be loaded first and others will be delayed until the user's action. To lazy load, we can:
    • Use the rerender attribute to perform a partial page load
    • Use JavaScript remoting to call actions in the controller
  • When using CSS in Visualforce pages, we have to be careful. The performance of Visualforce is directly affected by the optimization of the Visualforce. Here are some tips to increase the performance of CSS:
    • Use separate CSS files and refer to them in the Visualforce page (instead of writing the CSS code in the page itself). This will reduce the file size.
    • Use a single CSS file instead of using multiple CSS files. This will reduce the number of HTTP requests.
    • Refer to CSS files via static resources because it has a in-built caching mechanism.
    • When creating pages that have totally customized CSS (not using Salesforce CSS), do not forget to set the attribute of showHeaders and standardStylesheets of the <apex:page> tag to false.
  • When using JavaScript in Visualforce pages, we have to optimize them to increase the performance of Visualforce. Here are some tips to increase the performance of JavaScript:
    • Use separate JavaScript files and refer to them in the Visualforce page (instead of writing JavaScript in the page itself). This will reduce the size of individual pages taking advantage of browser caching.
    • Use a single JavaScript file instead of using multiple JavaScript files. This will reduce the number of HTTP requests and remove duplicate functions.
    • Use customized versions of JavaScript libraries which include only the required functions. This will reduce the file size.
    • If possible, use the <script> tag to include JavaScript in the Visualforce page and place it right before the </apex:page> closing tag. This will avoid loading of JavaScript before any other content in the Visualforce page.
    • Eliminate unwanted comments and whitespaces to reduce the file size and for faster downloads.
  • Use the escapeSingleQuotes method to avoid SOQL and SOSL injection attacks.
  • Images frequently play a major role in a Visualforce page. Therefore we have to optimize the usage of images in Visualforce pages using the following tips:
    • Use the CSS sprites instead of individual images. Using sprites, we can combine images (similar sized) into a single file. This will reduce the number of images used in the page and reduce the number of HTTP requests.
    • If possible, try to reduce the use of images and motivate the use of CSS.
    • Use static resources to refer to images in a Visualforce page.

Tip

View state cannot be viewed with tools such as Firebug because the view state data is encrypted.

Static resources

Static resources have an in-built caching feature and use the content distribution network built into Salesforce. The following are the advantages of using static resources to refer to CSS files, images, and JavaScript:
  • Use a static resource to display the content of another static resource with the action attribute of the<apex:page> tag. By doing this we can redirect from a Visualforce page to a static resource. Suppose we have a PDF as a static resource (named as helpPdf) and we use that static resource in the action attribute of the <apex:page> tag as follows:
    <apex:page sidebar="false" showHeader="false" standardStylesheets="false" action="{!URLFOR($Resource.helpPdf)}">
    </apex:page>
  • The URLFOR function plays a major role here. The redirection will not work properly without theURLFOR function. This is not limited to PDF; we can use any static resource to redirect.
    <apex:page sidebar="false" showHeader="false" standardStylesheets="false" action="{!URLFOR($Resource.helpStaticResource, 'index.htm')}">
    </apex:page>

Rendering PDFs

When we use components in a Visualforce page and the page is rendered as a PDF, these components do not always work. We must not use components that depend on JavaScript actions and Salesforce standard stylesheets.
  • The following components are safe to use in PDF rendering:
    • <apex:composition> (as long as the page contains PDF-safe components)
    • <apex:facet>
    • <apex:dataList>
    • <apex:define>
    • <apex:include> (as long as the page contains PDF-safe components)
    • <apex:insert>
    • <apex:image>
    • <apex:repeat>
    • <apex:outputLabel>
    • <apex:outputLink>
    • <apex:outputPanel>
    • <apex:outputText>
    • <apex:page>
    • <apex:panelGrid>
    • <apex:panelGroup>
    • <apex:param>
    • <apex:stylesheet> (as long as the URL isn't directly referencing Salesforce stylesheets)
    • <apex:variable>
  • The following components can be used with caution in rendering PDF (others are not safe to be used in PDF rendering):
    • <apex:attribute>
    • <apex:column>
    • <apex:component>
    • <apex:componentBody>
    • <apex:dataTable>

Using component facets

The <apex:facet> component is used to specify content in an area of a Visualforce page and it provides information about the data in the parent component. For example, we can use a facet component in the header or footer of a <apex:dataTable>. We can override the default facet of a Visualforce component by using the <apex:facet> component. The advantages and disadvantages of the facet component are as follows with an example:
  • The <apex:facet> component cannot be used directly in Apex; it must be a child component of another Visualforce component. We can use that in a dynamic component.
  • Facets only allow a single child within the start and close tags.
  • The following is an example of the <apex:facet> component that is used with the <apex:dataTable>component:
    <apex:page standardController="Item__c">
      <apex:pageBlock>
        <apex:dataTable value="{!item}" var="i">
          <apex:facet name="caption"><h1>This is {!item.Item_Name__c}</h1></apex:facet>      
          <apex:column>
          <apex:facet name="header">Name</apex:facet>
          <apex:outputText value="{!i.Item_Name__c}"/>
          </apex:column>
          <apex:column>
          <apex:facet  name="header">Unit Price</apex:facet>
            <apex:outputText value="{!i.Unit_Price__c }"/>
          </apex:column>
        </apex:dataTable>
      </apex:pageBlock>
    </apex:page>
  • We can use the facet component with <apex:actionSatus>. It is used to extend the displaying status indicator. This is explained in the following example:
    <apex:page>
      <apex:form >
        <apex:commandButton value="Facet with action Status" status="Status" rerender="rerenderBlock"/>
        <apex:pageBlock id="rerenderBlock">
        </apex:pageBlock>
        <apex:actionStatus id="Status">
          <apex:facet name="start">
            <img src="{!$Resource.LoadingAnimation}"/> 
          </apex:facet>
        </apex:actionStatus>
      </apex:form>
    </apex:page>


Popular posts from this blog

Visual Workflow

The benefits of Visual Workflow There are  certain benefits of using Visual Workflow. They are as follows: It allows you to create an automated business process using click not code. Visual Workflow does not require coding, and even if you do not know Apex code you can still develop business processes. Using screens, fields, and choices, you can implement complex business processes to make sure that your users are entering data in the right format. Through Visual Workflow, you can manipulate data for certain objects that are not available for the Workflow rule. For example, when a "contact role" is created or updated as primary for an opportunity then create a new task. It allows you to auto submit records for approval. You can post messages on Chatter. For example, if opportunity status gets Closed Won, post a message on Chatter group. It allows you to embed the Flow into the Visualforce page and using the Force.com Site you can expose it for ...

Visualforce fundamentals

Visualforce  is a web development framework that enables developers to build sophisticated, custom user interfaces for mobile and desktop apps that can be hosted on the  Force.com  platform. You can use  Visualforce  to build apps with user interfaces that look like the standard interface provided by  Force.com , as well as your own completely custom interface. Visualforce  enables developers to extend  Salesforce ’s built-in features, replace them with new functionality, and build completely new apps. Use powerful built-in standard controller features, or write your own custom business logic in  Apex . You can build functionality for your own organization, or create apps for sale in the  AppExchange . Visualforce  app development is familiar to anyone who has built web apps. Developers create  Visualforce  pages by composing components, HTML, and optional styling elements.  Visualforce  can integrate with ...