Lightning Videos

Refer the below link to get the complete series of the video

http://www.sfdcpanther.com/lightning-tutorial/

Advertisements

Dynamic Binding Salesforce Lightning Component(Generic)

Welcome back All, here we will learn about the dynamic field of Lightning Component. As Most of you must be aware of that In Lightning, Component Dynamic component is not available. Recently I was working on one of my projects and implemented the Dynamic binding using the lightning component so I am going to share how I implemented the same so that it may help others.

As we all know that we can use the Dynamic Binding in the VisualForce page but in Lightning Component it is not Possible. 

In this example, We will show the list of Objects in a picklist and when user will select any object it will dynamically show the TOP 15 records in a table.

Output 

OutPut.png

Step1 – Create Apex Class

DynamicBindingDemoController.class

Step2 – Create the Lightning Component

DynamicBindingDemo.cmp

See the comments into the component.

Step3: – Click on Controller from the right and paste the below code for Controller Javascript

DynamicBindingDemoController.js


({
doInit : function(component, event, helper) {
helper.onInit(component, event, helper);
},
doHandleChange : function(component, event, helper) {
helper.onHandleChange(component, event, helper);
},
})

Step4: – Click on Helper from the right and paste the below code for Helper Javascript

DynamicBindingDemoHelper.js


({
onInit : function(component, event, helper) {
/* Call the Apex class method to fetch the List of all object */
var action = component.get('c.listAllObject');
action.setCallback(this, function(response){
var state = response.getState();
if(state === 'SUCCESS' && component.isValid()){
/* set the value to the attribute of the component */
var responseValue = response.getReturnValue();
var lstOptions = [];
for(var i=0; i < responseValue.length; i++){
lstOptions.push({
value : responseValue[i].split('####')[1],
key : responseValue[i].split('####')[0]
});
}
lstOptions.sort();
component.set('v.objectList', lstOptions);

}else{
var errors = response.getError();
$A.log(errors);
if(errors || errors[0].message){
console(errors[0].message);
}
}
});
$A.enqueueAction(action);
},
onHandleChange : function(component, event, helper){
/* Call this method whenever user will select the Obejct
* and show the Dynamic Content */
var selObject = component.find('selectObject').get('v.value');
var action = component.get('c.listAllFields');
if(selObject!=null && selObject!='' && selObject!=undefined){
action.setParams({
"objectName" : selObject
});
action.setCallback(this, function(response){
var state = response.getState();
if( state === 'SUCCESS' && component.isValid()){
//component.find("dynamicBody").set("v.body",[]);
component.find('sfdcDiv').set("v.body",[]);
var responseValue = response.getReturnValue();
var objectValue = responseValue.sObjectData;
var fieldList = responseValue.fieldList;

/* Create Dynamic Table */
var sObjectDataTableHeader = [];
// Create table Header
for (var i=0; i < fieldList.length; i++) {
sObjectDataTableHeader.push(fieldList[i].label);
}
console.log(sObjectDataTableHeader);
//Get the count of columns.
var columnCount = sObjectDataTableHeader.length;
//Create a HTML Table element.
var table = document.createElement("TABLE");
//table.border = "1";
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = sObjectDataTableHeader[i];
headerCell.className='hearderClass';
row.appendChild(headerCell);
}
var dvTable = document.getElementById("sfdctable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
/* Create Dynamic Table End */

if(objectValue.length){
for(var j=0; j < objectValue.length; j++){
// Dynamic table Row
row = table.insertRow(-1);
// Dynamic Table Row End
for (var i=0; i < fieldList.length; i++) {
// Dynamic table Row
var cell = row.insertCell(-1);
cell.innerHTML = objectValue[j][fieldList[i].apiName];
component.set('v.isSending' , false);

}
}
}else{

}
}else{
var errors = response.getError();
$A.log('Error Details '+errors);
if( errors || errors[0].message){
console.log('Error Details '+errors[0].message);
}
}
});
$A.enqueueAction(action);
}else{
component.set('v.isSending' , false);
}
},
})

See the comments.

Step5: – Create Lightning Application

DynamicBindingDemoApplication.app

<aura:application access=”Global” extends=”force:slds” >
<c:DynamicBindingDemo />
</aura:application>

Click on Preview to see the output of the component.

Happy learning 🙂

Sharing is caring 🙂 😉

Resource:- 

OPFOCOUS Blog

Complete Code

 

 

 

Top 10 Features for Lightning Development – Spring 18 Release

New Lightning Components

Note: – The following components are new and require API version 42.0 and later.

  • lightning:carousel (Beta): – A collection of images that are displayed horizontally one at a time. As this is a beta version feature it will have some limitations.

base_carousel

  • lightning:formattedAddress: – Displays a formatted address that provides a link to the given location on Google Maps.

base_formattedAddress

  • lightning:inputAddress: – Input fields represents an address compound field with support for street, city, province, postal code, and country.

base_inputAddress.png

  • lightning:inputField : – An editable field with a label, help text, and value that corresponds to a field on a Salesforce object. This component must be nested in a lightning:recordEditForm component.
  • lightning:inputName: – Represents a name compound field with support for salutation, first name, middle name, last name, informal name, and suffix.

base_inputName.png

  • lightning:listView : – Represents a list view of records that you own or have read or write access to, and records shared with you.

base_listView.png

  • lightning:recordEditForm : – A record edit or record create layout that displays one or more fields provided by lightning:inputField.

base_inputField.png

  • lightningsnapin:prechatAPI : – Enables customization of the user interface for the pre-chat page in Snap-ins Chat.

Changed Lightning Components

lightning:datatable: – Datatable an amazing feature that we got in the previous release (winter 18) has many new features in the coming release Spring 18.

Text wrapping and clipping within a column is now supported. Text wrapping expands the height of the rows to reveal more content. Content is clipped by default if the number of characters is more than what the column width can hold. To toggle between the two views, select Wrap text or Clip text from the dropdown menu on the column header.Other features that are now supported include:

  • Appending icons to the header column
  • Header-level actions
  • Infinite loading of rows
  • Row-level actions
  • Selecting rows programmatically
  • Using a button as a data type

These features are captured by the following lists of attributes, column properties, and data types.

The following attributes are new.

  • enableInfiniteLoading—Enables or disables infinite loading. The default is false.
  • isLoading—Specifies whether more data is being loaded, and displays a spinner if there is. The default is false.
  • loadMoreOffset—Determines when to trigger infinite loading based on how many pixels the table’s scroll position is from the bottom of the table. The default is 20.
  • selectedRows—Enables programmatic row selection with a list of keyField values.
  • maxRowSelection—Maximum number of rows that can be selected. Checkboxes are used for selection by default, and radio buttons are used when maxRowSelection is 1.
  • onheaderaction—The action triggered when a header action is clicked. By default, it also closes the header actions menu.
  • onloadmore—The action triggered when infinite loading loads more data.
  • onresize—The action triggered when the table renders columns each time it resizes a column.
  • onrowaction—The action triggered when a row action is clicked. By default, it also closes the row actions menu.
  • rowNumberOffset—Determines where to start counting the row number. The default is 0.
  • showRowNumberColumn—Shows or hides the row number column. Set to true to show the row number column. The default is false.

The following column properties are new.

  • actions—Appends a dropdown menu of actions to a column.
  • cellAttributes—Provides additional customization, such as appending an icon to the output. You can pass in these attributes: iconName, iconLabel, iconPosition.
  • iconName—The Lightning Design System name of the icon. Names are written in the format standard:opportunity. The icon is appended to the left of the header label.

The following data types are now supported.

  • action—Displays a dropdown menu using lightning:buttonMenu with actions as menu items. This data type supports these typeAttributes properties: rowActions and menuAlignment.
  • button—Displays a button using lightning:button. This data type supports these typeAttributes properties: disabled, iconName, iconPosition, label, name, title, variant.

The url data type now supports the following typeAttributes property.

  • label—The text to display in the link. Give label of the record name or anything you want.

The date type now supports the following typeAttributes properties.

  • day—Valid values are numeric and 2-digit.
  • era—Valid values are narrow, short, and long.
  • hour—Valid values are numeric and 2-digit.
  • hour12—Determines whether the time is displayed as 12-hour. If false, time displays as 24-hour. The default setting is determined by the user’s locale.
  • minute—Valid values are numeric and 2-digit.
  • month—Valid values are 2-digit, narrow, short, and long.
  • second—Valid values are numeric and 2-digit.
  • timeZone—The time zone to use. Implementations can include any time zone listed in the IANA time zone database. The default is the runtime’s default time zone. Use this attribute only if you want to override the default time zone.
  • timeZoneName—Valid values are short and long. For example, the Pacific time zone displays as PST if you use short or Pacific Standard Time if you use long.
  • weekday—Valid values are narrow, short, and long.
  • year—Valid values are numeric and 2-digit.

 

Happy Reading 🙂

You can try all these features into the Sandbox Org once this release has been loaded into Sandbox after 5th Jan OR 6th of Jan 2018.

Resources: –

Salesforce Release Document

 

Play with Events in Lightning Component – Part 3

Application Event: – Whenever our component are not connected to each other and in that case we wanted to communicate between the components then we go for application event. We do not need to register the application event, handler is need to handle the application event.

Use Case: – When we want to communicate with the components that are not related to each other but need to reflect the data when there is any change in the other component. For example: – We have 2 components, 1st shows the List of All Contacts record and when we click on any contact we want to show the details of the contact then we will use Application Event.

In order to use Application event we need to follow the Four simple steps

  1. Create Application Event
  2. Fire the event from the child component
  3. handle the event into Parent Component
  4. Execute the action into Parent Component

Step 1 – Create Application Event

Open developer console and then File -> New -> Lightning Event -> name it applicationEvent and use below code.

<aura:event type=”APPLICATION” description=”Event template” >
<aura:attribute name=”testWord” type=”String” />
</aura:event>

Step 2 – Register the event

Unlike the Component we do not need to register the Application Event.

Step 3 – Fire the component Event

Use below code in javascript to execute the event.

({
handleClick : function(component, event, helper) {
    var appEvent = $A.get(‘e.c:applicationEvent’);
    appEvent.setParams({
            “testWord” : ‘Value From Application Event’
     });
     appEvent.fire();
   },
})

 

Explanation : –

  1. $A.get(‘e.c:applicationEvent’); – Finds the event with the name provided after c: and in our case it it applicationEvent.
  2. setParams : – is used to send the parameters to the parent component if we are using any attribute in the event. In our case we have used attribute testWord
  3. fire() :- Executes the event

Step 4: – Handle the Event in any Component

A single line of code to handle the event into the parent component

<aura:handler event=”c:applicationEvent” action=”{!c.doHandleCompEvent}” />

Explanation : –

  1. event: – Same as the type that we have provided at the time of registering the event
  2. action: – calls the java script controller method and there you can do rest of your stuffs

Step 5: – Do Action in JS controller

doHandleCompEvent : function(component, event, helper){

      var eventParam = event.getParam(‘testWord’);

     // getParams is used to get the parameters that we have passed from the child component

},

Note: – Both Application Event Handler and Application Event notifier component must be part of the same component. For example let call that component as aeContainer.cmp which will contain both the components.

<aura:component >
        <c:applicationEventComp1 />
        <c:HandlerComponent/>
</aura:component>

Happy Coding 🙂 😀

Resource :-

Complete Code

Salesforce Document

Play with Events in Lightning Component – Part 1

Events plays very important role while developing the Lightning component and communicating between the components.

Introduction :-

The Lightning framework uses event-driven programming. You write handlers that respond to interface events as they occur. The events may or may not have been triggered by user interaction.

In the Lightning Component framework, events are fired from JavaScript controller/helper actions. Events can contain attributes that can be set before the event is fired and read when the event is handled.

There are two types: component or application.

1- Component Events
A component event is fired from an instance of a component. A component event can be handled by the component that fired the event or by a component in the containment(Upper level) hierarchy that receives the event.
2 – Application Events
Application events follow a traditional publish-subscribe model. An application event is fired from an instance of a component. All components that provide a handler for the event are notified.

Main difference between application and component event is that Component event can only be handled by parent component and application event can be handled in all over the application.

Component Event needs to be register and handled wherever application event only need to handle and do not need to register.

In next post we will see how Component Event works and when to use component events while developing the custom lightning component.

Top 10 reasons why you should go for salesforce lightning?

I have compiled the reasons why one “Salesforce Developer” should go/adapt for Salesforce Lightning and are listed below –

  1. Avoid Server Calls: – Main advantage of Salesforce Lightning is that we can avoid many server calls while working with Lightning Components and reason behind this is JS controller using JS we can manipulate the data into the controller and display as per our need.
  2. Lazy Loading to increase performance – another awesome feature which loads/display the particular component or particular part of the component whenever users want to load not unlike the VF page. And because of lazy loading, it increases the performance and data will reflect on the fly. Uses a stateful client and stateless server architecture that relies on JavaScript on the client side to manage UI component metadata and application data.
  3. Faster Development: – Empowers teams to work faster with out-of-the-box components that function seamlessly with desktop and mobile devices. Building an app with components facilitates parallel design, improving overall development efficiency.
  4. Device-aware and cross-browser compatibility: – Apps use responsive design and provide an enjoyable user experience. The Lightning Component framework supports the latest in browser technology such as HTML5, CSS3, and touch events.
  5. Lightning App Builder: – Empowers the team/company/individual to develop the complete application without writing a single line of code using out of box functionality and this application will work well into Salesforce1 as well.
  6. Event-driven architecture: – Uses an event-driven architecture for better decoupling between components. Any component can subscribe to an application event, or to a component event they can see.
  7. SLDS: – SLDS means Salesforce Lightning Design System that gives you the power to style the component in your way, develop component as per your look and feel and you do not need to worry about responsive behavior it will take care all itself.
  8. 2 Way Binding: – It one of the Salesforce lightning feature that made me “Wow” and yes it is two-way binding Changes in the application state have been automagically reflected into the view and vise-versa. In fact, we could build our own directives with two-way data bound scope properties, by setting a configuration value.
  9. Avoid ViewState Error: – Another awesome feature is that we will never get view state error while working with the lighting component. 
  10. Lightning OUT: – Here comes the true power of Salesforce Lighting that is lightning OUT which gives you the power to take your lightning component to an external site and this is the thing that enables you to show Lighting Component into VF page.

 

Happy reading 🙂

Happy Lightning 🙂 😀

Resources: –

Salesforce Document

Lightning Out

Automatic style your VF into Lightning Experience – lightningStylesheets

After winter 18 release, you do not need to put external CSS into your VF page to make lightning ready. You can do this by following only three simple steps, Yes it is 100% right.

Salesforce has released a brand new tag lightningStylesheets which enable automatic style sheets to VF page to run into Lightning Environment.

You can put true or false as the value of the lightningStylesheets tag in apex page.

 

Follow three simple steps to make your VF page as lightning ready

  1. Make sure to check Available for Lightning Experience, Salesforce1, and Lightning Communities checkbox while developing VF page.
  2. Put lightningStylesheets=”true” syntax into page Tag.
  3. Put  tag on the top of the page.

VF page

Here is the code of VF page that I used for testing purpose.

<apex:page standardController=”Opportunity” tabStyle=”Opportunity” lightningStylesheets=”true” >
<apex:slds />
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection columns=”2″>
<apex:inputField value=”{!Opportunity.Name}” />
<apex:inputField value=”{!Opportunity.StageName }” /> <br/>
<apex:inputField value=”{!Opportunity.CloseDate}” />
</apex:pageBlockSection>
<apex:pageBlockButtons location=”bottom”>
<apex:commandButton action=”{!save}” value=”Save”/>
<apex:commandButton action=”{!cancel}” value=”Cancel”/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

You can see the demo image below

20171016_140900 (1).gif

 

Happy reading and coding 🙂

 

Use Lightning Component into VF page – Lightning OUT

Have you ever used lightning component into your VF page? Have you ever think why we should create VF page and Lightning Component for the same functionality?

In all of my projects that I am working, I have stopped creating VF pages and Yes, it is 80% true 🙂 but I used to work on VF page for those clients that are still into Salesforce Classic.

111

I always use my lightning component into my VF page and it is right approach as everyone(Meetups, Dreamforce, Webinars, Salesforce docs) are talking about Lightning and it is future.

In this tutorial, we will create a lightning component, its controller(.jsfile), and an apex class which will display a list of Account into Lightning Component.

We will create a Lightning Application which will extend lightning out js file and a VF page where we will call that Lightning Component.

All resources used in this tutorial are listed below and can be found at my Github Repo.

1 – AccountList.cmp – The component which displays the list of All the accounts

2 – AccountListController.js – JS file the controller of AccountList component to communicate with Apex class and set the data into the component attribute.

3 – AccountController.cls – The apex class to query account records.

4 – LightningOutDemoApp.app – The app which contains the AccountList component

5 – AccountListVF.vfp – The VF page, where we will call the lightning component.

Key points to remember: –

  1. use <apex:includeLightning /> tags at the beginning of VF page This component loads the JavaScript file used by Lightning Components for Visualforce.
  2. Lightning App must extend ltng:outApp library/interface.
  3. We can use $Lightning.use() many times into VF page but that must reference the same lightning app.
  4. We can only call those components that are referenced into the app.

LightningOutDemoApp.app

<aura:application access=”Global” extends=”ltng:outApp” >
                      <c:AccountList ></c:AccountList>
</aura:application>

Description of above code

access: – determines, if we can use the component throughout the Salesforce org or not acceptable values, are global, public, private

ltng:outApp: – Extending from ltng:outApp adds SLDS resources to the page to allow your Lightning components to be styled with the Salesforce Lightning Design System (SLDS). If you don’t want SLDS resources added to the page, extend from ltng:outAppUnstyled instead. using ltng:outApp we can access our lightning component into VF page or any external site.

AccountListVF.vfp

<apex:page >
<apex:includeLightning />

        <– div where we will embed our lightning component –>

<div id=”lightning” />
$Lightning.use(“c:LightningOutDemoApp”, function() {
$Lightning.createComponent(“c:AccountList”,
{
“VFpageValue” : “Woohoooo, Lightning Out is an amazing feature of Salesforce Lightning”
},
“lightning”,
function(cmp) {

});
});

</apex:page>

$Lightning.use(): – Refer the lightning application that we are using.

$Lightning.createComponent(): – Used to dynamically creating the lightning component.

You will find the complete code into my Github Repo.

Resources: –

Salesforce Document

Salesforce Document Lightning Out

Lightning Icon

Lightning Card

Debugging Lightning Component tips and trick

Unlike Apex we can not debug lightning component very easily. So, I have found some solution here it may help others while developing the lightning component.

1-256

In this post, I will tell you how to debug lightning component. I have faced the problem while debugging the lightning component. So, I am posting the blog here that will help the other Salesforce Developer that are working on Lightning Component.

Right Click on the Component that You want to Debug

Select Inspect Element

Inspect Element

Select Network Tab and then Select XHR tab

After you selected XHR tab, refresh the lightning component so that error can be reproduced if the error is while loading the component otherwise perform the action where you are getting the error like onclick, onchange or any client-side action.

Debug Track 1

1 – Select Network Tab

2 – Select XHR tab

3 – Filter the response (enter your apex class method which is being called on the action from javascript)

4 – Select filtered response

5 – Select Response tab, copy and paste the response into notepad and you will get the complete detail about the error.

Debug Track 2

If you have any questions please come up into the comment section with.

Invoke Apex Controller from Lightning Component

Hi Friends,

In this post, I will show you how to invoke apex class from Lightning Component. Yes, I know earlier I posted a blog which says that say no to Apex controller 😛 😛 but there are many business cases where we need to use apex class.

Invoking apex controller from the lightning component is as easy as A, B, C. We will also learn about apex:repeat which is same as for loop in the apex and aura:handler which works as a constructor in Visualforce.

Considerations: – 

We need to keep the below things in our mind before calling the apex method from component

1 – Method must be annotated as @AuraEnabled to call from the Lightning Component

2 – Method must be static

In this tutorial, we will create a component that will call an apex controller at the time of load and display a list of Accounts into the component.

— Login into Salesforce Developer Org and open developer Console. Create a lightning Component and name it AccountList.

<aura:handler name=”init” value=”{!this}” action=”{!c.doInit}” />

Name Must be init that indicated that this will act as a constructor.

The value must be {!this} and in the action attribute, you can call any method if Javascript and I will name it doInit.

AccountList.cmp

<aura:component controller=”AccountController”>

<!– List of Accounts to hold all the list of Accounts –>

<aura:attribute name=”accounts” type=”Account[]”/>

<!– Init method works as constructor for Lightning Component –>
<aura:handler name=”init” value=”{!this}” action=”{!c.doInit}” />

<ul>

<!– Iterate over the list of Accounts and show the Account Name –>
<aura:iteration items=”{!v.accounts}” var=”account”>
{!Account.Name}
</aura:iteration>
</ul>

</aura:component>

 

AccountListController.js

({   

doInit : function(component, event) {       

// Call the Apex Class Method from Javascript       

var action = component.get(“c.findAll”);       

// Callback which will fetch the response from Apex and set the value to Component        action.setCallback(this, function(a) {   

// Set the value in the Accounts List an attribute that we created into Apex Controller        

component.set(“v.accounts”, a.getReturnValue());                   

});       

// Place the Action in the Queue    

$A.enqueueAction(action);   

}

})

 

AccountController.cls(Apex Class)

 

public class AccountController {

// Apex method must be @auraEnabled so that it can be called from the JavaScript Controller
@AuraEnabled
public static List<Account> findAll() {
return [SELECT Id, name, industry, Type, NumberOfEmployees, TickerSymbol, Phone
FROM Account ORDER BY createdDate ASC];
}
}

In the last setp create lightning App and test the Application AccountListApp.app

Click on Preview from the right to show the result!

<aura:application extends=”force:slds” >

<c:AccountList></c:AccountList>

</aura:application>

Controller