Salesforce

Visualforce vs Lightning

Posted on Updated on

Hi

There are lots of questions in the mind of Salesforce developers regarding Lightning but the question which comes in every Salesforce developer’s mind is, will Lightning replace Visualforce?

You will be able to answer this question after exploring the Lightning Experience and VisualForce.

vfvslightning

Lightning Experience is not finished yet. There is plenty of work for developers to do just  building out the basic Salesforce application. Many things are working great, some things are working well in “Beta”. As it is in “beta” version  there are a number of things we just haven’t gotten to yet.

We are living in a multi device world where users are expecting highly interactive and immersive experiences literally at their fingertips. Companies like Google, Facebook are making user experience highly interactive using isolated components. Online forms now come with immediate error feedback when users enter invalid data. This interactivity is no longer a novelty, it’s the norm.

So what does this mean for us?

The Visualforce framework provides a robust set of tags that are resolved at the server-side and that work alongside standard or custom controllers to make database and other operations simple to implement. This is a page-centric web application model. It’s great for basic functionality, but it’s challenging to deliver the new, more dynamic experience that users expect. Fundamentally, this is because it relies on the server to generate a new page every time you interact with the application.

Lightning components are part of the new Salesforce user interface framework for developing dynamic web applications for desktop and mobile devices. They use JavaScript at the client-side and Apex at the server-side to provide the data and business logic. To deliver a more interactive experience, you need help from JavaScript on the client-side. In this new app-centric model, JavaScript is used to create, modify, transform, and animate the user interface rather than completely replacing it a page at a time. This model is exciting, interactive, and fluid.

Both the page-centric and app-centric models have their own advantages and both are here to stay. Combining the models lets applications deliver the right type of experience for the right use case.

Let’s explore the differences between Lightning and Visualforce.

Visualforce

UI Generation

  • Server-Side

Workflow

  1. User requests a page
  2. The server executes the page’s underlying code and sends the resulting HTML to the browser
  3. The browser displays the HTML
  4. When the user interacts with the page, return to step one.

 Advantages

  1. Tried and true model
  2. Easy to implement for greater productivity
  3. Naturally splits large applications into small, manageable pages
  4. Has built-in metadata integration

 Disadvantages

  1. Limited interactivity (aside from added JavaScript functionality)
  2. Higher latency

 Lightning

 UI Generation

  •  Client-Side

 Workflow

  1. The user requests an application or a component
  2. The application or component bundle is returned to the client
  3. The browser loads the bundle
  4. The JavaScript application generates the UI
  5. When the user interacts with the page, the JavaScript application modifies the user interface as needed (return to previous step)

Advantages

  1. Enables highly interactive and immersive user experiences
  2. Aligns with Salesforce user interface strategy
  3. Built on metadata from the foundation, providing an integrated developer experience
  4. The Developer Console supports Lightning components, so there’s an integrated developer experience

Disadvantages

  1. Higher learning curve compared to Visualforce
  2. Higher complexity than Visualforce—you’re building an application, not a page
  3. Since Lightning components are new, there are still some features that aren’t supported
  4. There are a limited number of out-of-the-box components

You have gone through pros and cons of Lightning and Visualforce now you have to decide which tool you should use.

Here are some guidelines to help you decide-which tool you should use and when.

When you should use Lightning

  • If you are developing for Salesforce1 Mobile Application you should use Lightning as visualforce characteristics, especially the page-centric orientation, can be a poor match for mobile apps with limited, high-latency network connections and limited compute resources. Lightning components, by contrast, was designed specifically to handle this context.
  • If you are building an interactive experience with JavaScript to meet user experience requirements you should use Lightning.
  • If you are enabling non-developers to build apps by assembling standard or custom components you should use Lightning App Builder and Lightning components for custom components. Use Visualforce if the required components aren’t yet available.
  • If you are adding user interface element for example, say you want to add a tab to a record home. This task is a simple drag-and-drop in Lightning App Builder.
  • If you are building a Community for Customers you should use Community Builder to create a Lightning-based community site leveraging Lightning components.
  • If you are committed to invest in latest technology you should start using Lightning Components.
  • If you are starting a brand new project you should use Lightning Components. If you’re not familiar with them, there’s no better time than now to learn!

Continue using Visualforce

  • If you are building a page-centric experience with limited Client-Side logic use Visualforce.
  • If you are committed to Javascript Framework such as AngularJS or React continue using Visualforce.
  • If you are building an interactive experience with Javascript and you need third party Framework you should use Visualforce as a container for third party Framework.
  • If you are building a community for partners continue using Visualforce in Salesforce Classic. Explore using Lightning components with Lightning components for Visualforce.
  • If you are exposing a Public-Facing Unauthenticated Website continue using Visualforce. Lightning components don’t support an anonymous (unauthenticated) user context yet.
  • If you are rendering pages as PDF in your application use Visualforce. Lightning components don’t support rendering as PDF output yet.
  • If you are adding to an existing project with lots of Visualforce Pages continue to use Visualforce. Consider moving to Lightning components using Lightning components for Visualforce.

Now you are able to decide which tool to use. But, because web applications are taking more advantage of the app-centric model, I will encourage all Salesforce developers to learn at least the basics of Lightning components. You’ll want to use these components in your future development work.

Oauth Salesforce with Lightning Out

Posted on

Hi All,

In this article, I will explain the code which can be used for connecting and getting the records
from different or multiple salesforce organization using Apex and Lightning Out.

To start first you need to authorize URLs which can be accessed from salesforce environment.
Go to Setup > Administration Setup > Security Controls > Remote Site Settings.

Create one CONNECTED APP go to SETUP > BUILD > CREATE > APP > CONNECTED APP > NEW.

Create Custom Setting for Version,Client Id,Client Secret. Go to SETUP > BUILD > DEVELOP > CUSTOM Settings.

After completing all the steps let’s start coding.

CallBackURLController.apxc :

public with sharing class CallBackURLController{

    @AuraEnabled
    public Static List<Contact> getContacts(String Accesscode){
    
        version__c vrsn = [select name, ClientId__c, ClientSecret__c from version__c limit 1];
        Accesscode = Accesscode.replace('=','%3D').trim();
        String redireUri = 'https://skdomain-dev-ed--c.ap2.visual.force.com/apex/callbackurl';
        String loginUri = 'https://login.salesforce.com';
        String header = '';
        String endpoint = '';
                
        String reqbody = 'grant_type=authorization_code' + '&client_id=' + vrsn.ClientId__c +
            '&client_secret=' + vrsn.ClientSecret__c + '&code=' + Accesscode + '&redirect_uri=' + redireUri;
        
        endpoint = loginUri + '/services/oauth2/token?' + reqbody;
        
        Map<String, object> mapReqBody = CallBackURLController.getHTTPResponse(endpoint, header, 'POST');
        
        header = string.valueOf(mapReqBody.get('token_type')) + ' ' + string.valueOf(mapReqBody.get('access_token'));
        endpoint = loginUri + '/services/oauth2/userinfo';
        
        ///// User Info       
        Map<String, object> mapReqInfoBody = CallBackURLController.getHTTPResponse(endpoint, header, 'POST');
        
        ///// Query Request
        Map<String, object> mapURI = (Map<String, object>) mapReqInfoBody.get('urls');
        
        string queryUri = string.valueOf(mapURI.get('query')).replace('{version}',vrsn.name);
        endpoint = queryUri + '?q=select+id,Name,Phone,Email+from+contact+where+phone+!=null+limit+1000';
       
        Map<String, object> mapReqQryBody = CallBackURLController.getHTTPResponse(endpoint, header, 'GET');
        string strCons = JSON.serialize(mapReqQryBody.get('records'));
        list<contact> lstCon = (list<contact>) JSON.deserialize(strCons, List<contact>.class);
        return lstCon;
    }
    
    public static Map<String, object> getHTTPResponse(String endpoint, String header, String method){
        HttpRequest req = new HttpRequest();  
        req.setMethod(method);
        req.setEndpoint(endpoint);
        if(header != ''){
            req.setHeader('Content-Type', 'application/json');
            req.setHeader('Authorization', header);
        }
        Http httpReq = new Http();  
        HTTPResponse res = httpReq.send(req);
        return (Map<String, object>)JSON.deserializeUntyped(res.getBody());
    }
    
}

This class is making a callout to other Salesforce Org and fetching Contacts of that Salesforce Org.

LightningOutApp.app :

<aura:application access="GLOBAL" extends="ltng:outApp">
    <aura:dependency resource="c:LightningOutCmp" />
</aura:application>

LightningOutCmp.cmp :

<aura:component controller="CallBackURLController" implements="force:appHostable">
    <aura:attribute name="code" type="String" default=""/>
    <aura:attribute name="contacts" type="Contact[]" />
    <aura:if isTrue="{!v.code==''}">
    	<ui:button label="login into Other Org" press="{!c.redirect}"/>
        <aura:set attribute="else">
        	<ui:button label="Get Contacts" press="{!c.getCons}"/>
        </aura:set>
  	</aura:if> 
    
    <div id="tblDiv" style="display:none">
        <table>
            <tr>
                <th>Name</th>
                <th>Phone</th>
                <th>Email</th>
            </tr>
            <aura:iteration items="{!v.contacts}" var="con">
               <tr>
                   <td>{!con.Name}</td>
                   <td>{!con.Phone}</td>
                   <td>{!con.Email}</td>
                </tr>
            </aura:iteration>        
        </table>
    </div>
</aura:component>

This component will be used in Visualforce Page.

LightningOutCmpController.js :

({
	redirect : function(component, event, helper) {
        window.location.href = 'https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=[YOUR CLIENT ID]&redirect_uri=[REDIRECT URL]&prompt=login&display=popup';        
    },
    getCons : function(component, event, helper) {
        document.getElementById("tblDiv").style.display = "block";
        var code = component.get("v.code");        
    	helper.getContacts(component, code);
    },
}

Redirect() function will redirct to the login page for Salesforce Login. getCons() function will get Contact from logged in Salesforce Org.

LightningOutCmpHelper.js :

({
    getContacts: function(component, code) {        
        var action = component.get("c.getContacts");
        action.setParams({
            "Accesscode": code
        });
        var self = this;
        action.setCallback(this, function(actionResult) {
            component.set("v.contacts", actionResult.getReturnValue());       
        });        
        $A.enqueueAction(action);
    },
})

CallBackUrlPage.page

<apex:page showHeader="false" sidebar="false" standardStylesheets="false">
 <!-- Lightning Resources-->
    <apex:includeScript value="/lightning/lightning.out.js" /> 
    <!-- JavaScript to make Remote Objects calls -->
    <script>
        var code="{!$CurrentPage.parameters.code}";
        
        $Lightning.use("c:LightningOutApp", function() {
            $Lightning.createComponent("c:LightningOutCmp",
                  { "code" : code },
                  "lightningComponent",
                  function(cmp) {
                    // any further setup goes here
            });
        });
    </script>
     
    <!-- Lightning Component -->
    <div id="lightningComponent"/>
</apex:page>

When completed it will look like this.

12204800_921217127916108_1436226568_n 12204574_921217134582774_409109935_n 12207968_921217131249441_1515473630_n 12208016_921217124582775_1057121612_n

 

When you click on “Login into Other Org” it will prompt you to login to salesforce. After logging in it will redirect you to Component Page and when you click on “Get Contacts” button it will fetch records from other Salesforce Org.

 

Lightning Component, Remote Objects and Visualforce Page

Posted on

Hi All,

In my last post I showed JavaScript Remoting with Lightning Component. In this post I will show you other feature of VisualForce with Lighting Component which is Remote Objects. The Visual Remote Objects supports basic DML operation like create read, update and delete in JavaScript without writing even a single line of Apex code.

You can read more about Remote Objects here at Harshit Pandey’s Blog.

Let’s walk through code

JSRemoteComp.cmp :

<aura:component>
    
    <ltng:require scripts="/resource/stockfiles/stockfiles/jquerymin.js" 
                  afterScriptsLoaded="{!c.myAction}"/>
    
	<aura:attribute name="accounts" type="Account[]"></aura:attribute>
    
    <!-- REQUIRED SLDS WRAPPER -->
    <div class="slds">
        <!-- Page Header -->
        <div class="slds-page-header">
            <div class="slds-grid">
                <div class="slds-col slds-has-flexi-truncate">
                    <h1 class="slds-text-heading--medium slds-truncate" title="Account Information">Account Information</h1>
                </div>
            </div>
        </div>
        <!-- TABLE - BADGE COMPONENT -->
        <table id="tb" class="slds-table slds-table--bordered">
            <thead>
                <tr class="slds-text-heading--label">
                    <th scope="col">
                        <span class="slds-truncate">Name</span>
                    </th>
                    <th scope="col">
                        <span class="slds-truncate">Phone</span>
                    </th>
                    <th scope="col">
                        <span class="slds-truncate">Active</span>
                    </th>
                </tr>
            </thead>
        </table><!-- TABLE - BADGE COMPONENT -->
    </div><!-- REQUIRED SLDS WRAPPER -->  
</aura:component>

This Lighting Component will output Accounts passed from VisualForce Page.

JSRemoteCompController.js :

({
	myAction : function(component, event, helper) {
		var accounts = component.get("v.accounts");
        var row = '<tbody>';
        accounts.forEach(function(account) {
            row += '<tr class="slds-hint-parent">';
            row += '<td data-label="activity">';
            row += '<span class="slds-truncate">'+account.get("Name")+'</span></td>';
            row += '<td data-label="confidence">';
            row += '<span class="slds-truncate">'+account.get("Phone")+'</span></td>';
            row += '<td data-label="confidence">';
            row += '<span class="slds-truncate">'+account.get("Active__c")+'</span></td>';
            row += '</tr>';
        });
        row += '</tbody>';
        jQuery('#tb').append(row);
        
	}
})

In order to display a Lightning Component in a Visualforce page, you need to construct a simple Lightning Application that is used as the bridge between the two technologies. This needs to have a dependency on the Lightning Component that will display the content, I used JSRemote in this case.

JSRemote.app :

<aura:application access="GLOBAL" extends="ltng:outApp">
    <aura:dependency resource="c:JSRemoteComp" />
</aura:application>

Once the app is in place, there is markup in the Visualforce page to tie things together – note that the Lightning Component is constructed dynamically via JavaScript, rather than being included in the page markup server side.

JSRemoteDemo.page :

<apex:page standardStylesheets="false" sidebar="false" showHeader="false">
    
    <!-- Lightning Resources-->
    <apex:includeScript value="/lightning/lightning.out.js" />
    <apex:stylesheet value="/resource/SLDS/assets/styles/salesforce-lightning-design-system-vf.css"/>
    
    <!-- Remote Objects definition to set accessible sObjects and fields -->
    <apex:remoteObjects >
        <apex:remoteObjectModel name="Account" jsShorthand="Warehouse" fields="Id,Name,Active__c,Phone"></apex:remoteObjectModel>
    </apex:remoteObjects>

    <!-- JavaScript to make Remote Objects calls -->
    <script>
        fetchWarehouses();
        function fetchWarehouses(){
            // Create a new Remote Object
            var wh = new SObjectModel.Warehouse();
            
            // Use the Remote Object to query for 10 warehouse records
            wh.retrieve({ limit: 100 }, function(err, records, event){
                if(err) {
                    alert(err.message);
                }
                else {
                    //Adding Lightning Component Here
                    $Lightning.use("c:JSRemote", function() {
                        $Lightning.createComponent("c:JSRemoteComp",
                              { "accounts" : records },
                              "lightningComponent",
                              function(cmp) {
                                // any further setup goes here
                        });
                    });
                }
            });
        }
    </script>
    
    <!-- Lightning Component -->
    <div id="lightningComponent"/>
    
    
</apex:page>

Output will look similar to this.

remoteobj

So That’s It.

Show Contacts on Google Map

Posted on Updated on

Hi All,

In this article I will tell you how you can show your Contacts with their Locations on Google Map.In this example I am using Social Profile pictures of Contacts to show on Map.If you want to see your Profile picture you have to login from any of your social profile.If you do not want to use Contact’s social profile, you can modify code to use Attachments related to these Contacts.

Screenshot_2015-10-13-10-39-49

Let’s walk through the code.

ContactsOnGoogleMapController Class :

public class ContactsOnGoogleMapController{
    
    public String contactJson{get;set;}
    
    public ContactsOnGoogleMapController(){
        
        List<Contact> conList = [select Id,Name,Email,Phone,MailingLatitude,MailingLongitude,MailingStreet,MailingCity,MailingState,MailingCountry,PhotoUrl from Contact Order By CreatedDate DESC LIMIT 5];
        
        String baseURL = 'https://ap2.salesforce.com';
        String coma = '';
        
        if(conList.size() > 0){
            contactJson = '[';
            
            for(Contact con : conList){
                contactJson += coma + '{\"title\":\"' + con.Name + '\",'+
                                '\"lat\": \"' + con.MailingLatitude + '\",'+
                                '\"lng": \"' + con.MailingLongitude +'\",'+
                                '\"address\": \"' + con.MailingStreet +' '+ con.MailingCity +'<br/>'+ con.MailingState + '<br/>' +con.MailingCountry + '\",'+
                                '\"contact\": \"' + con.Phone + '\",'+
                                '\"icon\": \"' + baseURL +''+ con.PhotoUrl + '\"}';
                                
                coma = ',';
            }
            
            contactJson += ']';
            
        }
    }
    
}

In this controller I am querying Contact’s records.From Contact List I am creating a JSON string to pass on VF Page.

ContactsOnGoogleMap VF Page :

<apex:page controller="ContactsOnGoogleMapController" showHeader="false" sidebar="false" standardStylesheets="false">

    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    
    <script type="text/javascript">
        var mapicon = JSON.parse('{!contactJson}');
        
        window.onload = function () {
            LoadMap();
        }
        function LoadMap() {
            var mapOptions = {
                center: new google.maps.LatLng(mapicon[0].lat, mapicon[0].lng),
                zoom: 8,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            var infoWindow = new google.maps.InfoWindow();
            var latlngbounds = new google.maps.LatLngBounds();
            var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
            
            for (var i = 0; i < mapicon.length; i++) {
                var data = mapicon[i]
                var myLatlng = new google.maps.LatLng(data.lat, data.lng);
                
                var image = {
                    url: data.icon,
                    size: new google.maps.Size(100, 65),
                    origin: new google.maps.Point(0, 0),
                    anchor: new google.maps.Point(17, 34),
                    scaledSize: new google.maps.Size(65, 65)
                };
                
                var marker = new google.maps.Marker({
                    position: myLatlng,
                    map: map,
                    title: data.title,
                    icon: image,
                    contact: data.contact
                });
                
                (function (marker, data) {
                    google.maps.event.addListener(marker, "click", function (e) {
                        infoWindow.setContent("<div style = 'width:100%;height:40%'><img width='60px' height='60px' align = 'middle' src = '" + data.icon + "' />&nbsp;&nbsp;<b>"+ data.title + "<b/><br/><a href=tel:["+data.contact+"]>"+data.contact+"<img style='vertical-align:top' width='20' height='18' src='/resource/dial'/></a><br/>"+data.address+"</div>");
                        infoWindow.open(map, marker);
                    });
                })(marker, data);
                latlngbounds.extend(marker.position);
         
            }
            
            var bounds = new google.maps.LatLngBounds();
            map.setCenter(latlngbounds.getCenter());
            map.fitBounds(latlngbounds);
        }
        
    </script>
    
    <div id="dvMap" style="width: 100%; height: 600px">
    </div>
    
</apex:page>

Above script is used to show Contacts with their information.

So That’s It.