logo

Visualforce Interview Questions and Answers

Visualforce, like HyperText Markup Language, is a tag-based markup language (HTML). Visualforce is a framework in Salesforce that allows developers to create custom user interfaces for their applications.

What it is:
* A markup language (similar to HTML) used to define the structure and behavior of Salesforce pages.
* Allows developers to create custom, interactive experiences beyond Salesforce’s standard UI.

How it works :
* Uses Visualforce pages, written with <apex:> tags (specific to Salesforce), to create forms, dashboards, and customized views.
* Can be combined with Apex (Salesforce’s programming language) to add business logic behind the scenes.
* Can reference standard controllers (to work with Salesforce objects like Accounts and Contacts) or custom controllers for more flexibility.

Example :
<apex:page controller="MyCustomController">
    <h1>Welcome to Visualforce!</h1>
    <apex:form>
        <apex:inputText value="{!myText}" />
        <apex:commandButton value="Submit" action="{!doSomething}" />
    </apex:form>
</apex:page>


* The {!myText} is a Visualforce expression, binding the input value to a controller variable.
* The button triggers the doSomething method in the Apex controller.

Visualforce is a web development framework created by Salesforce for building custom user interfaces and applications that integrate seamlessly with the Salesforce platform. It allows developers to create highly customized, dynamic, and interactive pages within Salesforce. Here are the key reasons to use Visualforce:

1. Custom User Interfaces :
* Tailored Experiences : Visualforce enables the creation of custom pages that match specific business needs, providing a more tailored user experience compared to standard Salesforce pages.
* Flexibility : Developers can design pages with custom layouts, styles, and functionalities that are not possible with standard Salesforce components.

2. Seamless Integration with Salesforce :
* Native Integration : Visualforce pages are tightly integrated with Salesforce data and functionality, allowing developers to leverage Salesforce's built-in features like objects, fields, and relationships.
* Access to Salesforce APIs : Visualforce can interact with Salesforce APIs, enabling advanced data manipulation and integration with external systems.

3. Extend Salesforce Functionality :
* Custom Logic : Visualforce allows developers to implement custom business logic using Apex (Salesforce's programming language), enabling complex workflows and processes.
* Enhanced Features : Developers can extend Salesforce's standard features by creating custom buttons, links, and actions.

4. Reusable Components :
* Custom Components : Visualforce supports the creation of reusable components, reducing development time and promoting consistency across applications.
* Standard Components : Developers can use standard Salesforce components or create custom ones to build pages faster.

5. Mobile-Friendly Development :
* Responsive Design : Visualforce pages can be designed to be responsive, ensuring they work well on mobile devices.
* Mobile-Specific Pages : Developers can create pages specifically optimized for mobile users.

6. Enhanced User Experience :
* Dynamic Content : Visualforce allows for dynamic content rendering based on user input or data, creating a more interactive experience.
* Custom Visualizations : Developers can create custom charts, graphs, and dashboards to visualize data in meaningful ways.

7. Security and Compliance :
* Salesforce Security Model : Visualforce pages adhere to Salesforce's robust security model, ensuring data security and compliance with organizational policies.
* Access Control : Developers can control access to Visualforce pages using profiles, permission sets, and sharing settings.

8. Scalability :
* Handles Large Data Volumes :Visualforce is designed to work efficiently with large datasets, making it suitable for enterprise-level applications.
* Performance Optimization : Developers can optimize page performance using techniques like pagination and lazy loading.

9. Integration with Other Technologies :
* JavaScript and CSS : Visualforce supports the use of JavaScript, CSS, and HTML, allowing developers to create rich, interactive interfaces.
* Third-Party Libraries : Developers can integrate third-party libraries like jQuery, Bootstrap, or D3.js for advanced functionality.

10. Legacy System Support :
* Migration Path : Visualforce is often used to migrate legacy systems to Salesforce by creating custom interfaces that replicate existing functionality.
* Backward Compatibility : Visualforce works well with older Salesforce implementations, ensuring compatibility with existing customizations.

11. Use Cases for Visualforce :
* Custom Forms : Create custom forms for data entry that go beyond the capabilities of standard Salesforce pages.
* Complex Dashboards : Build dashboards with custom visualizations and interactive elements.
* Customer Portals : Develop customer or partner portals with tailored interfaces.
* Embedded Applications : Embed Visualforce pages in Salesforce Lightning or external websites.
* Custom Workflows : Implement custom workflows and processes that are not supported by standard Salesforce features.

12. Limitations of Visualforce :
* Learning Curve : Requires knowledge of Apex and Visualforce markup, which can be challenging for new developers.
* Performance : Poorly designed Visualforce pages can lead to performance issues.
* Modern Alternatives : Salesforce Lightning (based on modern web standards) is increasingly preferred for new projects, though Visualforce remains relevant for specific use cases.

A Visualforce page in Salesforce is super versatile! You can use it in several places across the platform to create custom experiences. Let’s break it down! ?

1. Salesforce UI (Classic & Lightning Experience) :
  • Custom Tabs: Add a Visualforce page as a custom tab in Salesforce, similar to a standard object tab.
    • Great for creating custom apps or dashboards.
  • Page Layouts: Embed a Visualforce page within a record detail page (like Accounts, Contacts, or Opportunities).
    • Useful for showing related lists, charts, or dynamic content.
  • Home Page Components: Add Visualforce elements to the Salesforce Home page to provide custom notifications or summaries.
2. Lightning Experience & Salesforce Mobile App :
  • App Builder: Even though Visualforce was designed with Salesforce Classic in mind, it works in Lightning too!
    • You can add a Visualforce page as a Lightning Component within the App Builder.
  • Mobile Navigation: Visualforce pages can be mobile-friendly and included in the Salesforce mobile app menu.
3. Buttons, Links, and Actions :
  • Custom Buttons and Links: Use Visualforce pages to override standard Salesforce buttons (e.g., New, Edit, View).
    • Great for adding validation or multi-step wizards.
  • List View Buttons: Create mass actions using Visualforce pages and Apex.
4. Email Templates :
  • Use Visualforce to create dynamic, data-driven email templates.
    • Allows pulling related records or custom formatting beyond standard email templates.
5. Portals & Communities :
  • Salesforce Sites: Host Visualforce pages externally as public websites (without requiring users to log in).
  • Experience Cloud (Communities): Embed Visualforce pages to create custom user experiences for customers or partners.
6. External Systems :
  • Visualforce + Apex + REST/SOAP APIs: Build a Visualforce page that interacts with external systems — like fetching data from a third-party app or creating dynamic forms.
7. Custom Apps & Wizards :
  • Design multi-step wizards, custom navigation flows, or specialized apps within your Salesforce org.
Visualforce is a Salesforce framework for creating custom user interfaces using a tag-based markup language similar to HTML. It integrates with Salesforce through data binding, component-based architecture, security adherence, and Apex integration. Visualforce supports both standard and custom controllers for data manipulation.
Standard controllers in Visualforce provide basic CRUD operations for Salesforce objects, allowing developers to quickly build pages that interact with Salesforce data. For example, a Visualforce page using a standard controller for the Account object can include a form with input fields for the Account’s Name, Industry, and Phone, with built-in save and cancel actions.
Controller extensions in Visualforce extend the functionality of standard or custom controllers, adding custom logic or accessing additional data. They are defined using the “extensions” attribute in the <apex:page> tag. For example, an extension can add a method to retrieve an account name and a custom action to save the account and redirect to its detail page.
Pagination in Visualforce divides large datasets into smaller chunks for easier navigation. This can be implemented using the <apex:pageBlockTable> component and the StandardSetController class in Apex, which provides methods for pagination like next() and previous().

Let’s break this down! I’ll explain the difference between a standard controller and a custom controller in Salesforce — it’s a common question for Visualforce development. ?

1. Standard Controller :
What it is :
  • Provided by Salesforce, no Apex code required.
  • Automatically gives you basic operations for standard and custom objects (like View, Edit, Save, and Delete).
When to use :
  • When you only need basic CRUD (Create, Read, Update, Delete) functionality.
  • When you want to leverage built-in validation rules, security, and field-level access.
Example :
<apex:page standardController="Account">
    <h1>{!Account.Name}</h1>
    <apex:form>
        <apex:inputField value="{!Account.Phone}"/>
        <apex:commandButton value="Save" action="{!save}"/>
    </apex:form>
</apex:page>

* This uses the Account standard controller — Salesforce handles loading the record and saving changes automatically!


2. Custom Controller :
What it is :
  • Written in Apex, giving you complete control over the logic and data.
  • You define the methods (e.g., querying data, handling actions) and business rules.
When to use :
  • When you need custom business logic beyond standard CRUD operations.
  • When you need to work with multiple objects or make complex queries.
  • When you want to bypass standard security (field-level and object-level security are not enforced automatically with custom controllers).

Example :

Apex Controller :

public class MyCustomAccountController {
    public Account acc {get; set;}
    
    public MyCustomAccountController() {
        acc = new Account();
    }
    
    public PageReference saveAccount() {
        insert acc;
        return null;
    }
}

Visualforce Page :

<apex:page controller="MyCustomAccountController">
    <apex:form>
        <apex:inputField value="{!acc.Name}"/>
        <apex:commandButton value="Save" action="{!saveAccount}"/>
    </apex:form>
</apex:page>

* Here, the save logic is handled by the saveAccount method in the custom controller.


3. Controller Extensions
(Bonus!) :
What it is :
  • Hybrid approach — extends a standard controller with custom logic.
  • You get the best of both worlds: standard controller’s built-in functionality + custom logic.
Example :
public class MyAccountExtension {
    private final Account acc;
    public MyAccountExtension(ApexPages.StandardController stdController) {
        this.acc = (Account)stdController.getRecord();
    }
    
    public String getCustomGreeting() {
        return 'Hello, ' + acc.Name + '!';
    }
}

Visualforce Page :
<apex:page standardController="Account" extensions="MyAccountExtension">
    <h1>{!customGreeting}</h1>
</apex:page>
Quick Comparison :
Feature Standard Controller Custom Controller
CRUD Operations Automatic Manual (you write the logic)
Business Logic Limited Fully customizable
Security Enforcement Enforced automatically Must handle manually
Multiple Objects No Yes
Ease of Use Simple, quick to set up More effort, but flexible
9 .
How do you implement field-level security?
Field-level security in Visualforce controls user access to specific fields within Salesforce objects. It can be enforced declaratively or programmatically. Use the isAccessible, isCreateable, and isUpdateable methods in Apex to check field-level security before performing operations.
10 .
What are the security considerations when developing Visualforce pages?
When developing Visualforce pages, consider security aspects like data access control, input validation, XSS prevention, CSRF protection, and using HTTPS. These measures ensure the safety and integrity of the application and its data.
11 .
How can you optimize the performance of a Visualforce page?
Optimizing Visualforce page performance involves reducing view state size, using efficient SOQL queries, implementing pagination, leveraging caching, optimizing Apex code, minimizing JavaScript and CSS, and using Remote Objects for complex data operations.
* action : Calls a controller method.

* rerender : Updates part of the page without a full refresh.

* renderAs : Renders the page as a PDF or other format.

1. URL Parameters :

  • How it works : You append parameters to the end of the Visualforce page URL using a question mark (?) to start, and ampersands (&) to separate multiple parameters.

    • Example: /apex/MyPage?param1=value1&param2=value2
  • In Visualforce: Use {!$CurrentPage.parameters.paramName} to access the parameter values.


2. <apex:param> Tag :

  • How it works: Use this tag within <apex:commandLink> or <apex:commandButton> to pass parameters when navigating between Visualforce pages.

  • In Visualforce: The destination page can then retrieve these parameters using {!$CurrentPage.parameters.paramName}.


3. Apex Controller :

  • How it works: You can pass parameters to an Apex controller method through URL parameters or within <apex:actionFunction>.

  • In Apex: Use ApexPages.currentPage().getParameters().get('paramName') to retrieve the parameter values.


Important Considerations:

  • Security: Avoid passing sensitive information directly in the URL as it can be easily exposed.
  • Special Characters: URL parameters might need encoding to handle special characters correctly.
  • Data Types: Parameter values are typically treated as strings. You might need to convert them to other data types in your Apex controller.


Example: Passing parameters through URL


Visualforce Page :

<apex:page controller="MyController">
    <apex:outputLink value="/apex/AnotherPage?name=John&age=30">
        Click here to go to another page
    </apex:outputLink>
</apex:page>


Apex Controller :

public class MyController {
    // ...
}


Another Visualforce Page :

<apex:page controller="AnotherController">
    Name: {!name}
    Age: {!age}
</apex:page>


Another Apex Controller :

public class AnotherController {
    public String name {get; set;}
    public Integer age {get; set;}

    public AnotherController() {
        name = ApexPages.currentPage().getParameters().get('name');
        age = Integer.valueOf(ApexPages.currentPage().getParameters().get('age'));
    }
}

This example demonstrates how to pass parameters through the URL and retrieve them in both Visualforce and Apex.

 

 

 

14 .
What are the benefits and drawbacks of using Visualforce over other Salesforce UI technologies?
Visualforce is a mature and stable technology within Salesforce, offering server-side rendering, seamless Apex integration, and backward compatibility. However, it has limitations in interactivity, a steeper learning curve, less mobile optimization, and potential performance overhead compared to modern UI frameworks like Lightning Components.
15 .
Explain how Visualforce works with Salesforce Object Query Language (SOQL).
Visualforce pages interact with Salesforce data through controllers using SOQL. For example, a custom controller can fetch data from a Salesforce object, and the Visualforce page can display the queried data using components like apex:pageBlockTable.
Lightning web components adhere to current web standards, are easy to reuse both inside and outside the platform, are fast, and adapt well to various form factors. Converting Visualforce components to Lightning web components is a time-consuming procedure, but it allows you to improve and refine your programmes. Consider the overall design and usability of each component and its equivalent. Work with your designer to determine the best method to align your component with the Lightning Experience user interface's more modern appearance and feel. The component designs supplied in the Lightning Design System can be used for inspiration and sample code.

You must determine when to reuse a Visualforce page within Lightning Experience and when to rebuild it as a Lightning web component as you start constructing Lightning web components. If you wish to rebuild, seriously consider :

* The user experience is more engaging and responsive.

*
an easy-to-optimize experience for a variety of device types.

*
Your app will run more smoothly.

* The Lightning Experience low-code tools and Lightning web components are always recommended for new development. They provide numerous advantages and make the development process simpler.
A getter method is included in every standard controller and returns the record indicated by the id query string variable in the website Url. Using the! object syntax, the related page markup can reference attributes on the context record, where the item is the lowercase name of the item connected with the controller. A page that uses the Account standard controller, for example, can use an account. name to get the value of the name field for the user that is currently in context. You can retrieve data from linked records using merge field syntax, much like you do with queries in the Lightning Platform API:

* Up to five tiers of child-parent interactions are possible. For example, if you're working with the Contact standard controller, you may use! contact.Account.Owner.FirstName (a three-level child-to-parent connection) to get the name of the account record's owner.

* One level of parent-child relationships can be explored. If you're using the Account standard controller, for example, you can use your account. Click on Contacts to get an array of all the contacts linked with the account now in use.

In Visualforce, extensions are Apex classes that enhance the functionality of a page's controller. Here's a breakdown of what that means:

1. Controllers in Visualforce

  • Standard Controllers: Visualforce pages can use standard controllers, which provide basic functionality for interacting with a single Salesforce object (like Account or Contact). They handle common actions like saving, editing, and deleting records.
  • Custom Controllers: For more complex logic, you can create custom controllers in Apex. These classes define all the actions and data handling for your Visualforce page.

2. Why Use Extensions?

  • Extend Functionality: Extensions allow you to add new features or modify existing ones in a controller without completely rewriting it.
  • Leverage Standard Controllers: You can use an extension to build upon the functionality of a standard controller, overriding specific actions or adding new ones while still benefiting from the standard controller's built-in features.
  • Maintain User Permissions: When extending a standard controller, the standard controller's logic runs in user mode, respecting the permissions and field-level security of the current user.

3. How Extensions Work

  • Apex Class: An extension is an Apex class that has a constructor which accepts a single argument of type ApexPages.StandardController (for extending standard controllers) or the type of your custom controller.
  • extensions Attribute: You associate an extension with a Visualforce page using the extensions attribute of the <apex:page> tag.
  • Accessing Controller Methods: You can reference methods defined in your extension class within your Visualforce markup using {! } notation.

Example :

<apex:page standardController="Account" extensions="MyExtension">
    <h1>Account Name: {!account.Name}</h1>
    <apex:form>
        <apex:inputField value="{!account.Name}"/>
        <apex:commandButton value="Save" action="{!save}"/>
        <apex:commandButton value="Custom Action" action="{!myCustomAction}"/>
    </apex:form>
</apex:page>

 

public class MyExtension {
    private Account acc;

    public MyExtension(ApexPages.StandardController stdController) {
        this.acc = (Account)stdController.getRecord();
    }

    public PageReference myCustomAction() {
        // Perform some custom logic here
        return null;
    }
}

 

In this example, MyExtension extends the standard Account controller. It adds a new action myCustomAction while still allowing the page to use the standard save action.

Key Benefits of Extensions :

  • Code Reusability: You can reuse extension classes across multiple Visualforce pages.
  • Organization: Extensions help keep your controller logic organized and modular.
  • Maintainability: It's easier to maintain and update code when it's separated into logical units.

What is View State?

  • HTTP is Stateless: The Hypertext Transfer Protocol (HTTP) used for web communication is stateless. This means that each request from a web browser to a server is treated as a brand new request, without any memory of previous interactions.
  • Maintaining State: Visualforce pages often need to maintain state between requests. For example, a page might need to remember the values entered in a form or the results of a query.
  • View State as the Solution: Visualforce uses a mechanism called "view state" to preserve this state. It's essentially a snapshot of the page's data and component hierarchy at a particular point in time.


How View State Works :

  1. Serialization: When a Visualforce page is rendered, the framework serializes the relevant data (like component states, field values, and controller variables) into an encrypted string.
  2. Hidden Field: This encrypted string is stored in a hidden form field within the page.
  3. Round Trip: When the user interacts with the page (e.g., clicks a button), the view state is sent back to the server along with the request.
  4. Deserialization: The server deserializes the view state, restoring the page's previous state.
  5. Processing: The server processes the user's action, potentially modifying the data.
  6. Update: The view state is updated to reflect the changes.
  7. Response: The updated page, including the new view state, is sent back to the browser.


Key Considerations :

  • Size Limit: View state has a size limit (currently 135KB). Exceeding this limit will result in an error.
  • Performance: Large view states can impact page load times and performance, as they need to be serialized, transmitted, and deserialized.
  • Security: View state is encrypted to protect sensitive data.


Best Practices for Managing View State :

  • Reduce Data:
    • Use filters and pagination to limit the amount of data displayed on a page.
    • Use the transient keyword in Apex to exclude variables that don't need to be persisted across requests.
    • Optimize SOQL queries to retrieve only necessary data.
  • Minimize Components: Reduce the number of UI components on the page.
  • Use Read-Only Components: Consider using <apex:outputText> instead of <apex:inputField> for displaying non-editable data.
  • Leverage JavaScript Remoting: For certain scenarios, JavaScript remoting can reduce reliance on view state.


Monitoring View State :

  • Development Mode: Enable "Show View State in Development Mode" in your user settings to inspect the view state of a page.
  • Analyze: Use the view state tab in the development mode footer to identify which parts of your page are contributing most to the view state size.

By understanding how Visualforce handles view state and following best practices, you can build efficient and performant Visualforce pages.

20 .
What is the difference between outputField and inputField?

In Visualforce, both <apex:outputField> and <apex:inputField> are used to display data related to fields on Salesforce objects, but they serve different purposes:


<apex:outputField>

  • Read-only display: This component is used to display the value of a field in a read-only format. Users cannot directly edit the value displayed by an <apex:outputField>.
  • Respects field settings: It automatically respects the field's attributes defined in Salesforce Setup, such as:
    • Label: Displays the field's label.
    • Data type: Formats the value according to the field's data type (e.g., date, number, currency).
    • Required: Indicates if the field is required.
    • Help text: Shows help text when the user hovers over the field.
    • Field-level security: Enforces field-level security, preventing users from seeing fields they don't have access to.
  • Example :
  • <apex:outputField value="{!Account.Name}" />
This would display the Account Name in a read-only format, respecting the field's label and data type.


<apex:inputField>

  • Editable input: This component is used to display a field and allow users to edit its value. It renders an input element (like a text box, checkbox, or picklist) depending on the field's data type.
  • Respects field settings: Like <apex:outputField>, it also respects the field's attributes from Setup, including:
    • Label: Displays the field's label.
    • Data type: Provides an appropriate input element for the field's data type.
    • Required: Enforces required field validation.
    • Help text: Shows help text.
    • Field-level security: Enforces field-level security.
  • Example :
  • <apex:inputField value="{!Account.Name}" />

This would display the Account Name in an editable text box, allowing users to modify it.


Key Differences Summarized :

Feature <apex:outputField> <apex:inputField>
Purpose Read-only display Editable input
User Interaction Cannot edit Can edit
Input Element None Renders input element (text box, checkbox, etc.)
The style used for standard Salesforce pages associated with the specified object is automatically inherited by any page associated with a standard controller. That is, the tab for the supplied object is selected, and all page elements are styled with the tab's associated colour.

The tabStyle parameter on the <apex: page> element can be used to change the styling of a page that utilizes a standard controller. The following page, for example, utilizes the Account standard controller but outputs a page that accentuates the Opportunities tab and uses the yellow colour of the Opportunity tab:
<apex:page standardController="acunt" tabStyle="opp">
</apex:page>?
Maps convey data more accurately than just geographic data. Maps that use third-party mapping services are straightforward to develop with Visualforce mapping components. Visualforce maps are JavaScript-based interactive maps that include zooming, panning, and markers based on Salesforce or other data. Develop standalone map webpages, maps that can be inserted into page designs, and even Salesforce mobile maps.

Visualforce includes many mapping components. The <apex: map> component specifies the size, type, center point, and initial zoom level of the map canvas. The <apex:mapMarker> child component specifies the address or geolocation of the markers to be placed on the map (latitude and longitude). When a marker is clicked or tapped, the <apex:mapInfoWindow> component can be used to add configurable information panels.
Standard buttons, such as New, View, and Edit, can be overridden independently in Lightning Experience, mobile, and Salesforce Classic. When a user hits a regular, personalised, or external object tab, you can also change the tab home page.

* To override the home page of a normal button or tab:
* To override a button or tab's home page, click Edit next to it.
* As an override type, select the Visualforce page.
* When users click the button or tab, select the Visualforce page you want to execute.

You should use the normal controller for the item on which the button resides when overriding buttons with a Visualforce page. To utilize a website page to override the Edit button on accounts, for example, the standardController="Account" property on the <apex: page> tag must be included in the page markup.
 <apex: page standardController="Account">

 <!-- Website content >

 </apex:page>?
The apex:pagemessage element generates and presents all error codes from all elements on the current website page, with SF styling applied. When the apex:pagemessage element is used in a Visualforce page, this element will have various properties that will be used.

Apex pagemessage Component Attributes :

Title The title of the Error will be displayed.
Summary The summary of the title Error Message is printed with this parameter.
Detail This will display the Error's detailed description.
Severity This parameter is an Error logotype. Error, Warning, Info, and Confirm are the several types of error severity.
Strength The intensity message logo is available in sizes ranging from 1 to 3.
Rendered This property determines whether or not the element should be enabled.
Escape A Boolean value indicates whether vulnerable HTML and XML elements should be encoded in the HTML produced by this module.
Show Detail It's a Boolean type that determines whether the particular location of the messages is displayed; by default, it's false.
Dynamic Visualforce bindings allow you to create generic Visualforce web pages that help to visualize records without having to know which fields to display. In other words, rather than being defined at compile-time, the variables on the webpage are defined at run time. This enables a developer to create a web page that renders differently depending on the rights or preferences of different audiences. Dynamic bindings are useful for managed package Visualforce pages because they enable the analysis of information particular to each subscriber with very minimal work.

For both standard and custom objects, dynamic Visualforce binding is supported. The following is a general description of dynamic bindings :

reference[expression]

Where the syntax explains as follows :

* The value of the reference is either an sObject, global variable, or an Apex class.

* The name of a field or a related object is returned by the expression. If an associated object is provided, it can be used to pick fields or other related objects in a recursive manner.