Invoking REST API From Visualforce Page

Usually we make Rest API calls from Salesforce to External systems to get the data or to pass the updates to External Systems, using Apex class. But sometimes we can have a situation, like where we need to make a call to external systems from the visual force page.

Salesforce has introduced a concept called AJAX ToolKit, which help us to make REST API call from the JavaScript in Visualforce Page. Here is an example to invoke REST API from Visualforce Page. In below example I’m using https://exchangeratesapi.io/ web service HTTP callout and send a GET request to get the foreign exchange rates. The foreign exchange rates service sends the response in JSON format.

Visualforce Page:

<apex:page>
    <apex:includeScript value="//code.jquery.com/jquery-1.11.1.min.js" />
    <script>
    function apiCall() {
        //Get a reference to jQuery that we can work with
        $j = jQuery.noConflict();
        //endpoint URL
        var weblink = 'https://api.exchangeratesapi.io/latest?base=USD'; 
        
        $j.ajax({
            url: weblink,
            type: 'GET', //Type POST or GET
            dataType: 'json',
            beforeSend: function(request) {
                //Add all API Headers here if any
                //request.setRequestHeader('Type','Value');
            },
            
            crossDomain: true,
            //If Successfully executed 
            success: function(result) {
                //Response will be stored in result variable in the form of Object.
                console.log('Response Result' + result);
                
                //Convert JSResponse Object to JSON response
                var jsonResp = JSON.stringify(result);
                document.getElementById("apiData").innerHTML = jsonResp;
            },
            
            //If any Error occured
            error: function(jqXHR, textStatus, errorThrown) {
                //alert('ErrorThrown: ' + errorThrown);
            }
        });
    }
    </script>
    <apex:form>
        <!--call javaScript-->
        <input type="button" value="Call API" onclick="apiCall()" />
        <div id="apiData">
        </div>
    </apex:form>
</apex:page>

Salesforce Lightning Progress Bar

lightning:progressBar component displays the progress of an operation from left to right, like a file download or upload.

Here is an example loads the progress bar on load of the component, and in the JS controller that changes the value of the progress bar.

Lightning Component:

<!--ProgressBar.cmp-->
<aura:component>
     <!--declare handler for render the JS method for Progress bar-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
     <!--declare attributes for progress bar value-->
    <aura:attribute name="progress" type="Integer" default="0"/>
    <div class="slds-m-around_xx-large">
        <!--Lightning Progress Bar-->
        <lightning:progressBar value="{!v.progress}"/>
    </div>  
</aura:component>

Lightning Component JS Controller:

({
    //Specifying progress === 100 ? clearInterval(interval) : progress + 20 increases
    //the progress value by 20% and stops the animation when the progress reaches 100%
    //The progress bar is updated every 1000 milliseconds.
    doInit:  function (component, event, helper) {
        var interval = setInterval($A.getCallback(function () {
            var progress = component.get('v.progress');
            component.set('v.progress', progress === 100 ? clearInterval(interval) : progress + 20);
        }), 1000);
    }
})

Output:

Get Data From Visualforce Controller Extension Without SOQL Query

When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup. But we can use StandardController.addFields(List fieldNames) method, which adds a reference to each field specified in fieldNames so that the controller can explicitly access those fields as well.

public with sharing class AccountControllerExt {
    public Account acc {get; set;}
    
    public AccountControllerExt(ApexPages.StandardController controller) {
        List<String> accFieldList = new List<String>();
        //Passing a list of field names to the standard controller
        controller.addFields(new List<String>{'Id', 'Name', 'AccountNumber', 'Website', 'Phone','Type', 'Industry'});
        //Standard controller to retrieve the field data of the record
        acc = (Account)controller.getRecord();
    }
}

Padding String in Salesforce Apex

Left Pad:

leftPad(length): Returns the current String padded with spaces on the left and of the specified length. If length is less than or equal to the current String size, the entire String is returned without space padding.

String name = 'biswa';
String lpName = name.leftPad(8);
System.debug('LeftPad-' + lpName);
System.assertEquals('   biswa', lpName);

leftPad(length, padStr): Returns the current String padded with String padStr on the left and of the specified length. padStr to pad with; if null or empty treated as single blank.

Integer num = 555;
String lpString = String.valueOf(num).leftPad(5, '0');
System.debug('LeftPad-' + lpString);
System.assertEquals('00555', lpString);

Right Pad:

rightPad(length): Returns the current String padded with spaces on the right and of the specified length. If length is less than or equal to the current String size, the entire String is returned without space padding.

String name = 'biswa';
String rpName = name.rightPad(8);
System.debug('RightPad-' + rpName);
System.assertEquals('biswa   ', rpName);

rightPad(length, padStr): Returns the current String padded with String padStr on the right and of the specified length. padStr to pad with; if null or empty treated as single blank.

Integer num = 555;
String rpString = String.valueOf(num).rightPad(5, '0');
System.debug('RightPad-' + rpString);
System.assertEquals('55500', rpString);

Visualforce Pages with Lightning Experience Stylesheets

In Winter’18 release, Salesforce has introduced lightningStylesheets attribute. To style the Visualforce page to match the Lightning Experience UI when viewed in Lightning Experience or the Salesforce app, We can set lightningStylesheets="true" in the apex:page tag. When the page is viewed in Salesforce Classic, it doesn’t get Lightning Experience styling.

Here is a standard Visualforce page with the lightningStylesheets="true" attribute in Classic View and Lightning View.

Visualforce Page:

<apex:page standardController="Account" lightningStylesheets="true">
    <apex:form> 
        <apex:pageBlock>
            <apex:pageblockButtons location="bottom">
                <apex:commandButton action="{!Save}" value="Save"/>
                <apex:commandButton action="{!Cancel}" value="Cancel"/>
            </apex:pageblockButtons>
            <apex:pageBlockSection columns="2" title="Create Account">
                <apex:inputField value="{!Account.Name}"/>
                <apex:inputField value="{!Account.AccountNumber}"/>
                <apex:inputField value="{!Account.Phone}"/>
                <apex:inputField value="{!Account.Website}"/>
                <apex:inputField value="{!Account.Type}"/>
                <apex:inputField value="{!Account.Industry}"/>                
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Visualforce Page Classic View:

Visualforce Page Lightning View:

As of Winter’18 release, the following Visualforce components support the lightningStylesheets attribute or don’t require styling.

analytics:reportChart
apex:actionFunction
apex:actionPoller
apex:actionRegion
apex:actionStatus
apex:actionSupport
apex:areaSeries
apex:attribute
apex:axis
apex:barSeries
apex:canvasApp
apex:chart
apex:chartLabel
apex:chartTips
apex:column
apex:commandButton
apex:commandLink
apex:component
apex:componentBody
apex:composition
apex:dataList
apex:dataTable
apex:define
apex:detail
apex:dynamicComponent
apex:enhancedList
apex:facet
apex:flash
apex:form
apex:gaugeSeries
apex:iframe
apex:image
apex:include
apex:includeLightning
apex:includeScript
apex:inlineEditSupport
apex:input
apex:inputCheckbox
apex:inputField
apex:inputFile
apex:inputHidden
apex:inputSecret
apex:inputText
apex:inputTextArea
apex:insert
apex:legend
apex:lineSeries
apex:listViews
apex:map
apex:mapMarker
apex:message
apex:messages
apex:outputField
apex:outputLabel
apex:outputLink
apex:outputPanel
apex:outputText
apex:page
apex:pageBlock
apex:pageBlockButtons
apex:pageBlockSection
apex:pageBlockSectionItem
apex:pageBlockTable
apex:pageMessage
apex:pageMessages
apex:panelBar
apex:panelBarItem
apex:panelGrid
apex:panelGroup
apex:param
apex:pieSeries
apex:radarSeries
apex:relatedList
apex:remoteObjectField
apex:remoteObjectModel
apex:remoteObjects
apex:repeat
apex:scatterSeries
apex:scontrol
apex:sectionHeader
apex:selectCheckboxes
apex:selectList
apex:selectOption
apex:selectOptions
apex:selectRadio
apex:stylesheet
apex:tab
apex:tabPanel
apex:toolbar
apex:toolbarGroup
apex:variable
chatter:feed
chatter:feedWithFollowers
chatter:follow
chatter:newsFeed
flow:interview
site:googleAnalyticsTracking
site:previewAsAdmin
topics:widget