top of page

Considerations whilst writing Visualforce page

Updated: Jun 2, 2020

Using ApexPages.message to display error message for users


User custom controller when the page needs to be run in system mode


A controller extension is any Apex class containing a constructor that takes a single argument of type ApexPages.StandardController or CustomControllerName, where CustomControllerName is the name of a custom controller you want to extend.

Eg,

public class myControllerExtension {


private final Account acct;

// The extension constructor initializes the private member

// variable acct by using the getRecord method from the standard

// controller.

public myControllerExtension(ApexPages.StandardController stdController) {

this.acct = (Account)stdController.getRecord();

}


public String getGreeting() {

return 'Hello ' + acct.name + ' (' + acct.id + ')';

}

}

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

{!greeting} <p/>

<apex:form>

<apex:inputField value="{!account.name}"/> <p/>

<apex:commandButton value="Save" action="{!save}"/>

</apex:form>

</apex:page>


StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce list controllers provided by Salesforce.

public class opportunityList2Con {

// ApexPages.StandardSetController must be instantiated

// for standard list controllers

public ApexPages.StandardSetController setCon {

get {

if(setCon == null) {

List<account> accountList = [SELECT Name FROM Account LIMIT 20];

setCon = new ApexPages.StandardSetController(accountList);

//or

setCon = new ApexPages.StandardSetController(Database.getQueryLocator(

[SELECT Name, CloseDate FROM Opportunity]));

}

return setCon;

}

set;

}

<apex:page controller="opportunityList2Con">

<apex:pageBlock>

<apex:pageBlockTable value="{!opportunities}" var="o">

<apex:column value="{!o.Name}"/>

<apex:column value="{!o.CloseDate}"/>

</apex:pageBlockTable>

</apex:pageBlock>

</apex:page>

// Initialize setCon and return a list of records

public List<Opportunity> getOpportunities() {

return (List<Opportunity>) setCon.getRecords();

}

}


To get the value from Controller to Visualforce page, there should be a getter method defined in the Controller, but to pass value from Visualforce to Controller, it is not always necessary.


VF can display related object records that are up to five levels of child-parent and 1 level of parent-child relationships away.


The expression {!objectname.fieldname} makes a call to the getObject() method in the controller, which returns the recordid and then displays the fieldname for that record.


view state is automatically created to store state across multiple pages(i.e. its field values), such as in a wizard. It has a limit of 170kb.


Use custom and extension controllers to override existing functionality, customize navigation, use callsouts and web services..


Custom controller use no argument constructor.


A getter method is required in the custom controller to get values from the controller to the VF page.

A setter method is not always necessary to pass values from VF into controller as long as its bound to an sobject that is stored in a controller and the sobject is saved by a corresponding action method:

public class MyController {


private final Account account;


public MyController() {

account = [SELECT Id, Name, Site FROM Account

WHERE Id = :ApexPages.currentPage().getParameters().get('id')];

}


public Account getAccount() {

return account;

}


public PageReference save() {

update account;

return null;

}

}

<apex:page controller="myController" tabStyle="Account">

<apex:form>

<apex:pageBlock title="Congratulations {!$User.FirstName}">

You belong to Account Name: <apex:inputField value="{!account.name}"/>

<apex:commandButton action="{!save}" value="save"/>

</apex:pageBlock>

</apex:form>

</apex:page>


Instead of using getter and setter, use Apex properties.

Note - set method is executed before the action method.

Eg:

public class General {

private String StaticMember = 'hello';


public String myGoodStaticProp {

get {return StaticMember;}

set { StaticMember = value; }

}

public PageReference Save(){

return null;

}

}

<apex:page controller="General">

<apex:form>

<apex:inputText value="{!MyGoodStaticProp}"/>

<apex:commandButton value="Save" action="{!Save}" />

<apex:outputText value=" the value you entered is {!MyGoodStaticProp}" />

</apex:form>

</apex:page>



Use the 'rendered' attribute to show a section based on a boolean condition or using a function that returns a boolean value, for eg, {! not(isnull(accounts))}".


To prevent Prevent Cross-Site Request Forgery (CSRF)

CSRF setting at Setup -> Security Controls -> Session Settings.


Remove any state-changing operations from the apex:page action handlers.

Eg, do not add action attribute in the <apex:page>

<apex:page controller="CSRF_Demo" sidebar="false" action="{!performInitAction}" tabStyle="CSRF_Demo__tab">


To prevent XSS use the following:

Validate the input date against defined values

Output encoding to ensure only appropriate characters are displayed:

Eg: String input = <String variable>.escapeHTML4();

All standard Visualforce components that start with<apex> have anti-XSS filter.

Value that is going to be parsed by Javascript parser, use JSENCODE():

It encodes text and merge field values for use in JavaScript by inserting escape characters.

Eg: The following merge field in the script should be JSENCODED:

<script>

var x = '{!$CurrentPage.parameters.userInput}';

</script>

<script>

var x = '{!JSENCODE($CurrentPage.parameters.userInput)}';

</script>

Value that is going to be parsed by the HTML parser, use HTMLENCODE().

It is required when the default platform encoding is turned off or when you’re adding user-controllable input directly to the DOM.

Eg: The following merge field within the HTML tag should be HTMLENCODED

<apex:outputText escape="false" value="<i>Hello {!Account.Name}</i>" />

<apex:outputText escape="false" value="<i>Hello {!HTMLENCODE(Account.Name)}</i>" />

Value that is going to be parsed by both use JSINHTMLENCODE:

Eg: within the html tag Javascript is embedded so encode the merge field:

<div onclick="console.log('{!JSINHTMLENCODE(Account.Name)}')">Click me!</div>


To reference a static HTML file on a separate domain, use $IFrameResource.<resource_name> as a merge field, where resource_name is the name you specified when you uploaded the resource. For example:

<apex:iframe src="{!$IFrameResource.TestHtml}" id ="theiframe" width="500" height="500"/>


To refer to to an image loaded in a third party site:

<apex:image value= "{!IMAGEPROXYURL('<url>')}" />


To test Visualforce page in Lightning Experience, you can type the following into your JavaScript console:

$A.get("e.force:navigateToURL").setParams(

{"url": "/apex/pageName"}).fire();

or

For something a little more convenient to use, add the following bookmarklet to your browser’s menu or toolbar.

javascript:(function(){

var pageName = prompt('Visualforce page name:');

$A.get("e.force:navigateToURL").setParams(

{"url": "/apex/" + pageName}).fire();})();

Recent Posts

See All
Reference to a page in Visualforce

//refererence to google page PageReference pageRef = new PageReference('http://www.google.com'); //reference to the saved Visualforce...

 
 
 

Comments


Post: Blog2_Post

©2020 by SalesforceDemystified. Proudly created with Wix.com

bottom of page