Using Lightning Out

There is a plugin which is Lightning out to use the lightning component on any app ( Heroku, Visualforce, Node.js)

Lightning out is a framework inside the lightning to connect outside world servers and it will connect using the special library available called/lightning/lightning.out.js and has to be included in visualforce to consume the lightning component

Let’s start to understand what is Lightning Out? and How it will connect visualforce page and Lightning Component.

In this demo, I am retrieving the contacts of accounts and showing on the view.

ApexClass to retrieve contacts

public class ligtningoutCls {
    @AuraEnabled
    public static list<contact> getContacts(Id accId){
        return [select id,Name from contact where accountId =: accId];
    }

}

Create a Simple Lightning Component to Account Information.

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId" 
                controller="ligtningoutCls">
    <aura:attribute name="recordId" type="Id"/>
    <aura:handler name="init" value="{!this}" action="{!c.getContantList}"/>
    <aura:attribute type="contact[]" name="contacts"/>
    <table class="slds-table slds-table_bordered slds-table_cell-buffer">
        <thead>
            <tr class="slds-text-title_caps" >
                 <th scope="col">Id</th>
            	 <th>Name</th>
            </tr>
        </thead>
        <tbody>
             <aura:iteration items="{!v.contacts}" var="con">
                 <tr>
                     <td class="slds-truncate" scope="row">{!con.Id}</td>
                     <td class="slds-truncate" scope="row">{!con.Name}</td>
                 </tr>
            </aura:iteration>
        </tbody>
    </table>
</aura:component>

 

({
  getContantList : function(cmp, event, helper) {
        console.log(cmp.get("v.recordId"));
        var action = cmp.get("c.getContacts");
        action.setParams({
            accId : cmp.get("v.recordId")
        });
        action.setCallback(this,function(res){
            var state = res.getState();
            if(state ==='SUCCESS'){
                cmp.set("v.contacts",res.getReturnValue());
            }
        })
        $A.enqueueAction(action);
  }
})

Now create the lightning App and associate the above created lightning component.

<aura:application extends="ltng:outApp" >
    <aura:dependency resource="c:lightningOutCmp"/>
</aura:application>

<aura:dependency /> is a dependency tag and telling the application, that there are some dependencies to run the application.

Now Finally create the visual force page

with lightningOutVFpage

<apex:page standardController="Account">
   
    <apex:includeLightning />
    <div id="lightning" />

    <script>
        $Lightning.use("c:lightningOutApp", function() {
          $Lightning.createComponent("c:lightningOutCmp",
          {'recordId': '{!Account.Id}'},
          "lightning",
          function(cmp) {
          });
        });
    </script>
</apex:page>

https://yourDomainName.visual.force.com/apex/testLighthingOut?id=AccountId

here is the list of contacts on my display,

 

Global Action to Make Me owner of a record

Before Lightning Data Service, In order to save a record, we have to create the server method to process every request to save the information. By using Lightning Data Service we can reduce all unwanted server call and handle all the processing inside the controller.

In this scenario, I am explaining how to Own a Record in a button click.

Lightning gives us more flexibility when adding the action to the page layout.  So here is the common use case for all the object actions, which is Make Me the Owner. This can be used on any object (Case, Account, Contact, Lead, Custom Object).

we can change the Owner right inside client Controller within a lightning component.

Name this component as makeMeOwner

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <aura:attribute type="object" name="targetObject"/>
    <aura:attribute type="object" name="targetObjectError"/>
    <force:recordData aura:id="forceRecordCmp"
        recordId="{!v.recordId}"
        fields="Id,OwnerId"
        mode="EDIT"
        targetFields="{!v.targetObject}"
        targetError="{!v.targetObjectError}"
        recordUpdated="{!c.doInit}"/>
    
</aura:component>

Click the controller from the lightning menu.

({
  doInit : function(cmp, event, helper) {
        var record = cmp.get("v.targetObject");
        record.OwnerId  = $A.get("$SObjectType.CurrentUser.Id") //current user Id
        cmp.set("v.targetObject",record);
        helper.handleSaveRecord(cmp, event, helper);
  }
})

Helper Class

({
  handleSaveRecord: function(component, event, helper) {
        component.find("forceRecordCmp").saveRecord($A.getCallback(function(saveResult) {
            if (saveResult.state === "SUCCESS" || saveResult.state === "DRAFT") {
                console.log("Save completed successfully.");
            } else if (saveResult.state === "INCOMPLETE") {
                console.log("User is offline, device doesn't support drafts.");
            } else if (saveResult.state === "ERROR") {
                console.log('Problem saving record, error: ' + 
                           JSON.stringify(saveResult.error));
            } else {
                console.log('Unknown problem, state: ' + saveResult.state + ', error: ' + JSON.stringify(saveResult.error));
            }
        }));
    }
})

Create a Global Actions from the setup and refer the above-created Lightning Component.

Next, drag this action from theSalesforce1 and Lightning Actions to the Salesforce1 and Lightning Experience Actions and save the page layout.

 

 

Get Current User Id Information in Lightning

Getting a Current User Info used to be a hurdle in lightning before Winter 18.

We have to call apex method to return system.UserInfo.getUserId() now we no longer have to do this method.

In the Lightning Controller, we just need to call the $A.get(“$SObjectType.CurrentUser.Id”) to get the information

var userId = $A.get("$SObjectType.CurrentUser.Id");
Console.log(userId);

This helps in reducing unnecessary calls between the server and client.

URL hack workaround using lightning component

In Classic, URL hack is used by everyone and there are so many scenarios to use URL hack. One of the most used scenarios is to avoid the Record Type selection in the Custom Links/Buttons.

In the Summer ’17 release, Salesforce introduced Navigate to Custom Tabs More Easily with Friendly Tab URLs

This functionality allows us to use Lightning Component for URL Hacks. For this new approach, we have to create a Lightning Component and a Lightning Component Tab that refers to the Component

From the Developer Console create a Lightning Component  and name it, for example “recordTypeSelectionCmp” and paste the below code

<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction,force:appHostable" access="global" >
 
 <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
 
</aura:component>

Click the Controller and paste the below code

({
  doInit : function(component, event, helper) {
    var PageURL = decodeURIComponent(window.location.search.substring(1)); //You get the whole decoded URL of the page.
        var URLVariables = PageURL.split('&'); //Split by &amp;amp; so that you get the key value pairs separately in a list
        var ParameterName;        
        var objectName;
        var recordType;
    console.log(URLVariables)
        for (var i = 0; i &amp;lt; URLVariables.length; i++) {
            ParameterName = URLVariables[i].split('='); //to split the key from the value.			
            if (ParameterName[0] === 'recordType') { //getting the recordType Info
               recordType = (ParameterName[1]  === undefined ? 'Not found' : ParameterName[1]);            }
            else if (ParameterName[0] === 'objectName') { //getting the object Info
                objectName = (ParameterName[1] === undefined ? 'Not found' :ParameterName[1]);
            }
        }
        var createRecordEvent = $A.get("e.force:createRecord");
        createRecordEvent.setParams({
            "entityApiName": objectName,
            "recordTypeId" : recordType
        });
        createRecordEvent.fire();
  }
})

Now create the Lightning Tab from setup/Home and find “Tabs” in the Quick find.

Provide Tab Name, Tab Label, Tab Style and select the created component from the Lightning Component Picklist and save the tab.

Next, open the tab with the recordType and objectName variable in the URL, Please note ObjectName should be exact API name for example:

www.yourDomainName.lightning.force.com/one/one.app?recordType=01241000001ELa0AAG&objectName=Account#/n/recordType

Once you open the URL, you will see Record Type will be auto-populated.