Lightning

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.

 

Why use Lightning? and not other JS Frameworks

Posted on Updated on

Salesforce introduced Salesforce1 Lightning Components last year(2014) at Dreamforce. Lightning components give you a client-server framework based up JavaScript that is native to the Salesforce1 platform. It comes complete with an event-driven architecture that is optimized for fast Single Page Apps. If you are familiar with frameworks like AngularJS, Backbone and React you will know how Salesforce1 Lightning Framework is better from these frameworks.

build-nextgen-apps-faster-with-lightning-components-7-638

AngularJS : 

It was first released in 2009 and made available as open source framework under MIT license. Ever since its release, Angular ecosystem has grown beyond imagination. It currently boasts the biggest community of developers and is the most used JavaScript framework for developing Single Page Web Applications. AngularJS framework gives super powers to HTML by adding all the necessary features required to build dynamic views (interactive user interface). It gives option to extend HTML attributes by the use of Angular directives. Extending HTML with AngularJS is very simple, one can use standard AngularJS directive or develop a custom directive and use it on any div. Two way data binding is at the core of Angular.js.

BackboneJS :

It was first released in 2010 by Jeremy Ashkenas as open source JavaScript Framework under MIT license. It is a lightweight JavaScript Framework, it is simple, small size package and easy to learn. You can get started building apps with Backbone JavaScript Framework within no time. It is growing slow even though biggies like Pinterest, Foursquare, Walmart, Disqus are using backone.js. The main reason for that appears to be the sluggish release cycle of backbone and lack of power features that other frameworks offer out of the box. It is useful but more as a side framework rather than the core framework of your web project.

React :

ReactJS was first released as open source in 2013 under BSD license.React.js JavaScript Framework is behind the user interface of Facebook as well as Instagram. This gives us a quick idea about how powerful is ReactJS when it comes to building large scale applications of extreme dynamic nature. The community is growing rapidly ever since its release and it is the fastest growing JavaScript framework as of today. One can find tons of resources, tutorials and React component libraries to get going within no time. ReactJS is best at rendering complex user interfaces with high performance. The basic fundamental behind React is the concept of virtual DOM. ReactJS utilizes a virtual DOM, which can be rendered either at client side or server side and communicate back and forth. When the data manipulation is much more dynamic and complex, client side DOM manipulations become performance intensive.

Lightning Components : 

Lightning is different from above frameworks it is designed first and foremost for enterprise applications. Lighting has a rich event driven architecture that appeals to JavaScript developers and all of the power of the Force.com platform. The power of the component framework is in its ease of customization. Developers can combine multiple components into larger ones or even applications.

Lighting components encapsulate functionality, markup and CSS into reusable functional units that can be assembled into larger components or complete application. Using appHostable tag you can expose your component in Salesforce1 and it will become a mobile application.

Like other component frameworks where you typically have to roll your own backend functionality, authentication and connectivity, with Lightning you simply expose server-side Apex functionality with a single annotation and then instruct the component to utilize it.And now you have access to workflow, data validation, queues, bulk processing, reporting, dashboards much more.

Below are the features which tell you, why use Lightning and not other JS Framework?

  1. Lightning is NATIVE to Salesforce.
  2. INTEGRATED with Salesforce1.
  3. Commercial AppExchange
  4. Support OTHER JavaScript frameworks.
  5. METADATA
  6. EXTENDABLE and Resuable across apps and orgs.
  7. Encapsulated markup, logic and style.
  8. Responsive UI
  9. Loose coupling with a publish/subscribe eventing model.

Will Lightning applications and components replace other JS Frameworks? May be but time will tell. Should you get started building Lightning components now? Absolutely Yes!!!  🙂

 

Referencing Apex Map in Lightning Component

Posted on Updated on

Hi All,

In this post will show you, how to reference Apex Map in Lightning Components?
In visualforce, you can directly process map using markup. But in Lightning Component you can’t process map using Lightning Markup.

Here is the complete code.Let’s walk through code

MapDemoController.apxc :

public class MapDemoController{
    
    @AuraEnabled
    public static Map<Id,Contact> getContacts(){
        Map<Id,Contact> conMap = new Map<Id,Contact>([SELECT Id,FirstName,LastName,Phone,Email FROM Contact LIMIT 100]);
        
        return conMap;
    }
}

getContacts() method is passing a Map of contact to Lightning Component.

MapDemoComp.cmp :

<aura:component controller="MapDemoController">
	<ltng:require styles="/resource/SLDS/assets/styles/salesforce-lightning-design-system-vf.css"/>
	<!-- Attribute Definition -->
    <aura:attribute name="contacts" type="Map" />
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <div class="slds">
        <div id="contactDetail"></div>
    </div>
    
</aura:component>

aura:attribute type is defining type to Apex Map. Defining this map in this component is of no use as I am not using this map in the component directly.
But if you are passing map from some other component/app, this can be used to assign map.

MapDemoCompController.js :

({
	doInit : function(component, event, helper) {
		var action = component.get("c.getContacts");//Fetching Map from Controller
        action.setCallback(this, function(a) {
            component.set("v.contacts", a.getReturnValue());//Set return value to Contact Map
            var contacts = component.get("v.contacts");//Getting Map and Its value
            
			var tile='<ul class="slds-list--vertical slds-has-cards">';
			
            for (key in contacts){
                tile += '<li class="slds-list__item">';
                tile += '<div class="slds-tile slds-tile--board">';
                tile += '<div class="slds-tile__detail">';
                tile += '<p class="slds-text-heading--medium">'+ contacts[key].FirstName+' '+ contacts[key].LastName +'</p>';
                tile += '<p class="slds-truncate">Email - '+ contacts[key].Email +'</p>';
                tile += '<p class="slds-truncate">Phone - '+ contacts[key].Phone +'</p>';
                tile += '</div>';
                tile += '</div>';
                tile += '</li>';
            }
            tile += '</ul>';
            document.getElementById("contactDetail").innerHTML = tile;            
        });
        $A.enqueueAction(action);
	}
})

component.set(“v.contacts”, a.getReturnValue()) is used to set “v.contacts” map.
component.get(“v.contacts”) is used to get “v.contacts” map.
I could directly assign returned value from a.getReturnValue() to javascript variable. But to show you how you can set or get map, I did in this way.
contacts[key].FieldName is used to retrieve value from map.

🙂