Sunday, April 7, 2019

LightningOut in Salesforce

Expose Lightning component outside of lightning/salesforce

We can expose any component to outside of salesforce(it may be PHP/Wordpress/Sharepoint) or to classic VF page with usage of lightning Out.

We will directly jump to code and will see how to setup this.

Lets create a Component which you want to expose to VF page.

Component :LightningDataTableExample.cmp

<aura:component controller="AccountDataTableController" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" > <aura:attribute type="Account[]" name="acctList"/> <aura:attribute name="mycolumns" type="List"/> <aura:handler name="init" value="{!this}" action="{!c.fetchAcc}"/> <lightning:datatable data="{! v.acctList }" columns="{! v.mycolumns }" keyField="id" hideCheckboxColumn="true"/> </aura:component>

Add apex controller for the component 

public class AccountDataTableController { @AuraEnabled public static List <Account> fetchAccounts() { //Qyery 10 accounts List<Account> accList = [SELECT Id, Name, BillingState, Website, Phone, Industry, Type from Account LIMIT 10]; //return list of accounts return accList; } }

Lets add controller code for the component

({
    fetchAcc : function(component, event, helper) {
        helper.fetchAccHelper(component, event, helper);
    }
})


Lets add helpercode for the component

({ fetchAccHelper : function(component, event, helper) { component.set('v.mycolumns', [ {label: 'Account Name', fieldName: 'Name', type: 'text'}, {label: 'Industry', fieldName: 'Industry', type: 'text'}, {label: 'Phone', fieldName: 'Phone', type: 'Phone'}, {label: 'Website', fieldName: 'Website', type: 'url '} ]); var action = component.get("c.fetchAccounts"); action.setParams({ }); action.setCallback(this, function(response){ var state = response.getState(); if (state === "SUCCESS") { component.set("v.acctList", response.getReturnValue()); } }); $A.enqueueAction(action); } })
Add this component in Page and it will look like below


Now lets expose this component in classic VF page. To achieve this we wil luse lightning out with lightning dependency app

Create a new Lightning app with below code to expose the component to app

App:LoutDataTableApp.app

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

Lets create a vf page and display this component in VF page.

Vf Page: LODataTable.vfp

<apex:page >
    <apex:includeLightning />   
    <div id="LcDisplayId"></div>     
 <script>     
    $Lightning.use("c:LoutDataTableApp", function() {      
    $Lightning.createComponent("c:LightningDataTableExample",
    {
       
  },
   "LcDisplayId",
    function(component) {
        
    });
 });
 </script>
</apex:page>

Lets see the same Lightning component in classic VF page