LIGHTNING
Salesforce Lightning


1. What are the type of events into Salesforce Lightning component?
a. Application Event – Scope of this event is throughout the lightning App and any component which has registered for this event would get a notification.
b. Component Event– Scope of this event is within itself or the parent component of this event, all the components declared within the parent component would get notified of this event.
c. System Event- these are the events fired by Salesforce’s system during the lifecycle of the lightning app.
b. Component Event– Scope of this event is within itself or the parent component of this event, all the components declared within the parent component would get notified of this event.
c. System Event- these are the events fired by Salesforce’s system during the lifecycle of the lightning app.
2. What are the basic differences between Application Event and Component Event?
Component events are used to do communication between child and parent. They use bubbling and capture same as used in DOM events. A change in a child component can be communicated to the parent component via component event. Application events are used to communicate any change in the component to a broader audience. Any component who has registered for this event will get a notified.
To use Component Event API we use the below syntax
3. When should we use Component event and application events?
It is best to always use a component event instead of an application event. Component events can only be handled by components above them in the containment hierarchy, therefore, their usage is localized to the components that need to know about them.
Application events are best used for something that should be handled at the application level, such as navigating to a specific record. Application events allow communication between components that are in separate parts of the application and have no direct containment relationship.
4. Which interface we are supposed to implement so that a lightning component can be used as quick action?
We need to implement the following “force: lightningQuickAction” so that we can use the component as a Quick Action
5. Which interface we are supposed to implement so that a lightning component can be used as a Tab?
We need to implement the following “force:appHostable” so that we can use the component as a Tab
6. How can we use a lightning component in a VisaulForce Page? Explain?
A Lightning component can be embed in any webpage using a very powerful and flexible feature, Lighting out. When used with Visualforce some complexity becomes simpler.
Lightning component can be added to Visualforce page in three steps:
Lightning component can be added to Visualforce page in three steps:
1. We have to first Add the Lightning Components for Visualforce JavaScript library to your targetted Visualforce page using the tag.
2. Next we have to create and refer a Lightning app which is used to the component dependencies.
3. Lastly we need to write a JavaScript function which will finally create the the component on the page using $Lightning.createComponent()
7. How can we call child component controller method from the parent component controller method?
To call a child component’s controller method, we need to first create a aura:method which is publically accessible, aura:method is used to communicate down the containment hierarchy i.e. parent to child. Sample code for implementing the aura method:
Component code
Component code
Controller
({
publicmethod: function(cmp, event) {
var params = event.getParam(‘arguments’);
if (params) {
var message = params. str;
console.log(“message: ” + message);
return message;
}
}
})
({
publicmethod: function(cmp, event) {
var params = event.getParam(‘arguments’);
if (params) {
var message = params. str;
console.log(“message: ” + message);
return message;
}
}
})
Calling the cild method from parent controller
({
callchildCompMethod : function(component, event, helper) {
var childCmp = component.find(“childCompName”);
var Result =
childCmp. publicmethod (“message sent by parent component”);
console.log(“Result: ” + Result);
}
})
({
callchildCompMethod : function(component, event, helper) {
var childCmp = component.find(“childCompName”);
var Result =
childCmp. publicmethod (“message sent by parent component”);
console.log(“Result: ” + Result);
}
})
8. What are the different Lightning component bundles?
a. Component
b. Controller
c. Helper
d. Style
e. Document
f. Design
g. SVG
h. Rendrer
a. Component
b. Controller
c. Helper
d. Style
e. Document
f. Design
g. SVG
h. Rendrer
9. How to ensure FLS while working with Lightning Component?
FLS and CRUD are not automatically enforced in the lightning component whenever any object is referenced in the Apex Controller and the component will display the fields and records for which the users do not have access. Therefore we should manually enforce the FLS and CRUD in the Apex Controller, or we should try to use Lightning Data service wherever possible because it takes care of FLS and CRUD for us.
10. How can we use Lightning Components with the Salesforce1 Mobile App ?
For this purpose we need to first make a lightning tab which points to the lightning component we created and then we have to include that tab in the salesforc1 Mobile Navigation select list and the newly created tab to it.
11. Can we make a Lightning Component that shows up in both the mobile and the desktop user interfaces?
Lightning component is lightning experience ready by default and is also compatible in Salesforce1 App, it has a responsive layout therefore it adjust its resolution according the screen size and therefore can be used on desktop as well without writing any separate code.
12. Is Lightning component framework an MVC framework ?
No it is not a MVC framework it is a component based framework and event driven.
13. Which parts of Lightning Components are server-side and which are client-side ?
Lightning components have two types of controller, one which uses javascript and responds to the event occurring in the components at client side and the second controller which is an apex class. Method of apex controller are accessed by the JavaScript controller methods asynchronously.
14. Can we make one component inherit styles/CSS from a parent component, or must we always define it in the component ?
Child component inherits the CSS from its aren’t we do not need to specify it for each component
aura:method is used to communicate down the containment hierarchy i.e. parent to child
16. Can we Include One Lightning component to another ?
Yes we can include one Lightning component in another Lightning component
17. Is there any limit on how many component to have in one Application?
There is no limit on number of components defined within an application by salesforce
18. Is Lightning Components replacing Visualforce?
No Lightning component is not replacing Visualforce, Visualforce is still supported by Salesforce.
19. What is Aura? Why do we use the aura: namespace in the code?
Aura is a UI framework for developing dynamic web apps for mobile and desktop devices. Aura provides a scalable long-lived lifecycle to support building apps engineered for growth.
Aura supports partitioned multi-tier component development that bridges the client and server. It uses JavaScript on the client side and Java on the server side.
20. Do we need a namespace to develop Lightning Components?
You can have namespace in your org but it is not necessary to have a namespace to develop lightning component.
21. What are the tools included in lightning?
Lightning App Builder – It is a tool with User interface to use drag and drop functionality and create app fast by reusing the components, components can be standard or custom depending upon your requirement.
Lightning Component Framework- it provides a bundle that can be used to build reusable custom components, Standalone App and to customize Salesforce1 App
Lightning Connect – it is a powerful tool to facilitate the integration of force.com app with an external data source using OData specification
Lightning Process Builder – it is a visualization tool to build automation required for your business processes.
Lightning Schema Builder – it is a visualizing tool to view, create objects fields and relationship among them.
Lightning Component Framework- it provides a bundle that can be used to build reusable custom components, Standalone App and to customize Salesforce1 App
Lightning Connect – it is a powerful tool to facilitate the integration of force.com app with an external data source using OData specification
Lightning Process Builder – it is a visualization tool to build automation required for your business processes.
Lightning Schema Builder – it is a visualizing tool to view, create objects fields and relationship among them.
22. What is difference between Visualforce Components and Lightning Components?
Visualforce page is created keeping page as the center of the application and most of its calculation is performed at the server side. Lightning component on the other hand are created using the component based framework, most of the calculations are performed at the client side and makes the more dynamic and provide rich customer experience, also lightning component are build using mobile first approach.
23. Does Lightning work with Visualforce ?
Yes Lightning component works with Visualforce by implementing Lightning out as discussed earlier.
24. Are there any CSS (styles) provided by salesforce.com as part of the supported Lightning Components ?
Salesforce has provided lightning design system as the default css to be used with Lightning component.
25. Are Lightning Components intended only for mobile apps?
Although lightning framework creates component keeping mobile first approach, but its responsive design helps in providing the same experience over the desktop without writing separate lines of code
26. What are the advantages of lightning?
There are many advantages of using lightning like its out of the box component set which enables the fast paced creation of new apps, its event driven architecture which enables the easy decoupling between the components. Device awareness, cross browser compatibility and framework optimized for the performance.
27. Can we integrate Lightning components with another framework, such as Angular?
Yes we can integrate lightning with any 3rd party framework.
28. Can we include external JavaScript/CSS libraries in components?
It is possible to use custom CSS and JAvascriipt in the Lightning component
29. What happens with existing Visualforce Pages in Lightning Experience?
Most of the Visualforce page can be easily converted to lightning experience, but they are still supported by the salesforce and are not required to be converted
30. Where we can display lightning component?
Lightning component can be displayed at following places:
1. Lightning Experience
2. Salesforce1 App
3. Template-based Community
4. Standalone Lightning App
5. Visualforce Pages (Using Lightning out )
1. Lightning Experience
2. Salesforce1 App
3. Template-based Community
4. Standalone Lightning App
5. Visualforce Pages (Using Lightning out )
31. Do I always create an app bundle first when develop lightning component ?
No it is not necessary to create an Appp Bundle first to develop the lightning component
32. How can we deploy components to production org?
Lightning component can be deployed to the production via change sets, force.com IDE, Managed Package.
33. What is Lightning Experience?
It is the new user Interface developed by salesforce team, which is built on component based framework and event driven architecture, which provides a dynamic and responsive Experience to the user. This framework is built to provide optimum performance by using stateful Client side and stateless Server architecture
34. What is the use of implements in lightning component?
Implements is use to refer platform interfaces which enables a component to be used in different contexts or to grant access to extra context data, a component can implement more than one interfaces.
35. What is aura:registerevent in lightning component?
aura:registerevent is the notifier component and it declares that it may fire a particular event, it includes ‘name’ attribute which is relevant only to component event and is not used for application event. Other attribute is the ‘type’ which lets the component know which event would be fired.
Ex. <aura:registerEvent name=”Event” type=”c:EventName”/>
36. How can we subscribe to an event in lightning component?
To subscribe to an event in lightning component we need to include tag in the containment hierarchy. Subscription of these event depends on the event type i.e. component event or application event. For Component event we write below code.
In this ‘name’ attribute in should be exactly as name attribute in tag in the component which has fired the component. The ‘action’ attribute of sets the client-side controller action to handle the event. The ‘event’ attribute specifies the event being handled.
For Handling Application event we write below code
For Handling Application event we write below code
‘Event’ and ‘action’ attribute are same as the component event handling, it is just that we do not include ‘name’ attribute to handle the application event.
37. How can we communicate between two component?
In Lightning Component Framework, the communication between two component is accompalished supported in several ways.
1. Attributes or Methods to pass data down the component hierarchy
2. Lightning Events to pass data up and around in the component hierarchy
1. Attributes or Methods to pass data down the component hierarchy
2. Lightning Events to pass data up and around in the component hierarchy
38. What is aura definition bundle?
It represents a Lightning definition bundle, it contains a Lightning definition and all its related resources. It could define a component, application, event, interface, or a tokens collection.
An AuraDefinitionBundle component is a collection of component definition files, each representing a different resource such as markup code, event documentations, applications and interfaces.
Lightning bundles must be under a top-level folder that’s named aura. Each bundle must have its own subfolder under the aura folder.
A bundle doesn’t have a suffix but definition files can have one of these suffixes
Suffix Component Type
Suffix Component Type
Suffix
| Component Type |
.app | Application |
.cmp | Component |
.design | Design |
.evt | Event |
.intf | Interface |
.js | Controller, Helper, or Renderer |
.svg | SVG image |
.css | Style |
.auradoc | Documentation |
.tokens | Tokens collection |
39. What is aura:attribute?
They are same as member variable in apex classes, they are typed fields and are instance of a component. Attribute helps in making component more dynamic.
All attributes have a name and a type can be marked required by specifying ‘required=true’and can also have a default value. It has a naming rule as well:
1. Must begin with a letter or an underscore
2. Must contain only alphanumeric or underscore characters
2. Must contain only alphanumeric or underscore characters
40. What is lightning: or ui: in any lightning component?
Lightning has provided us with common User Interface components in the ui namespace which are used in the lightning component framework. They are ui:input and ui:output provide easy to implement common user interface.
Component with lightning namespace also provides us with the user interface but on top of that they include lightning design system CSS by default so we do not have to worry about the styling of these components.
41. How can we extend any component?
Component with lightning namespace also provides us with the user interface but on top of that they include lightning design system CSS by default so we do not have to worry about the styling of these components.
41. How can we extend any component?
To make a component extendable we need to set value of ‘extensible’ attribute as ‘true’ of the aura:component tag.
When a component extends another component it inherits all of the helper methods and attributes
When a component extends another component it inherits all of the helper methods and attributes
42. How to register, fire and handle a component and application event?
We register an event by by using the following code
<aura:registerEvent name=”sampleComponentEvent” type=”c:compEvent”/>
We fire event as shown below:
var compEvent = cmp.getEvent(“sampleComponentEvent”);
compEvent.fire();
Handle component event as below :
<aura:handler name=”sampleComponentEvent” event=”ns:eventName”
action=”{!c.handleComponentEvent}” phase=”capture” />
Handle Application event as below:
<aura:handler event=”c:appEvent” action=”{!c.handleApplicationEvent}”/>
43. Let’s say that you have an app myApp.app that contains a component myCmp.cmp with a ui:button component. During initialization, the init() event is fired in what order?
ui:button, ui:myCmp, and myApp.app.
44. Why do we use @AuraEnabled annotation?
The AuraEnabled annotation provides support for Apex methods and properties to be used with the Lightning Component framework.
The AuraEnabled annotation is overloaded, and is used for two separate and distinct purposes.
1. Use @AuraEnabled on Apex class static methods to make them accessible as remote controller actions in your Lightning components.
2. Use @AuraEnabled on Apex instance methods and properties to make them serializable when an instance of the class is returned as data from a server-side action.
The AuraEnabled annotation is overloaded, and is used for two separate and distinct purposes.
1. Use @AuraEnabled on Apex class static methods to make them accessible as remote controller actions in your Lightning components.
2. Use @AuraEnabled on Apex instance methods and properties to make them serializable when an instance of the class is returned as data from a server-side action.
45. Why do we use $A.enqueueAction(action)?
It adds the server-side controller action to the queue of actions to be executed. Rather than sending a separate request for each individual action, the framework processes the event chain and batches the actions in the queue into one request. The actions are asynchronous and have callbacks.
46. Use of THIS CSS class?
This adds namespacing to CSS and helps prevent one component’s CSS from blowing away another component’s styling.
47. What are the different ways to conditionally display markup, and what is the preferred approach?
Using the <aura:if> tag
Use CSS to toggle visibility of markup by calling $A.util.toggleClass(cmp, ‘class’) in JavaScript code.
Use CSS to toggle visibility of markup by calling $A.util.toggleClass(cmp, ‘class’) in JavaScript code.
47. What is $Resource global value provider? Is it possible to obtain a reference to a static resource in Javascript code?
It lets you reference images, style sheets, and JavaScript code you’ve uploaded in static resources.
To obtain a reference to a static resource in JavaScript code, use $A.get(‘$Resource.resourceName’).
48. Let’s say you have several buttons that reuse the same onclick handler. How will you retrieve the name of the button that fired the event?
Use event.getSource() in the client-side controller to get the button component that was clicked. Call
getLocalId() to get the aura:id of the clicked button.
49. What are the names of interfaces that are added to a Lightning component to allow it to be used as custom tabs, and to be used in Lightning and Community builder?
‘force:appHostable’ Allows a component to be used as a custom tab in Lightning Experience or the Salesforce app
‘forceCommunity:availableForAllPageTypes’ To appear in Community Builder, a component must implement the forceCommunity:availableForAllPageTypes interface
‘forceCommunity:availableForAllPageTypes’ To appear in Community Builder, a component must implement the forceCommunity:availableForAllPageTypes interface
50. What is the use of force:hasRecordId interface?
Add the force:hasRecordId interface to a Lightning component to enable the component to be assigned the ID of the current record.
The recordId attribute is set only when you place or invoke the component in a context of a record. For example, when you place the component on a record page, or invoke it as an action from a record page or object home. In all other cases, such as when you create this component programmatically inside another component, recordId isn’t set, and your component shouldn’t depend on it.
The recordId attribute is set only when you place or invoke the component in a context of a record. For example, when you place the component on a record page, or invoke it as an action from a record page or object home. In all other cases, such as when you create this component programmatically inside another component, recordId isn’t set, and your component shouldn’t depend on it.
51. What is Lightning Design System (SLDS)?
The Salesforce Lightning Design System (SLDS) component library is actively developed to enable Salesforce developers to create a uniform look and feel across all Salesforce-related applications while adhering to CSS best practices and conventions.
52. What is the use of access=“global”?
The framework enables you to control access to your applications, attributes, components, events, interfaces, and methods via the access system attribute. The access system attribute indicates whether the resource can be used outside of its own namespace.
You can specify these values for the access system attribute.
You can specify these values for the access system attribute.
Private: Available within the component, app, interface, event, or method and can’t be referenced outside the resource. This value can only be used for or .Marking an attribute as private makes it easier to refactor the attribute in the future as the attribute can only be used within the resource.
Accessing a private attribute returns undefined unless you reference it from the component in which it’s declared. You can’t access a private attribute from a sub-component that extends the component containing the private attribute.
Accessing a private attribute returns undefined unless you reference it from the component in which it’s declared. You can’t access a private attribute from a sub-component that extends the component containing the private attribute.
Public: Available within your org only. This is the default access value.
Global: Available in all orgs.
53. What is Lightning Data Services?
They are similar to a standard controller in Apex coding, advantages of using lightning Data service are mentioned below
1. Use Lightning Data Service to load, create, edit, or delete a record in your component without requiring Apex code.
2. Lightning Data Service handles sharing rules and field-level security for you.
3. In addition to not needing Apex, Lightning Data Service improves performance and user interface consistency.
1. Use Lightning Data Service to load, create, edit, or delete a record in your component without requiring Apex code.
2. Lightning Data Service handles sharing rules and field-level security for you.
3. In addition to not needing Apex, Lightning Data Service improves performance and user interface consistency.
54. What are Local and Global ids with respect to lightning component?
Component IDs
A component has two types of IDs: a local ID and a global ID. You can retrieve a component using its local ID in your JavaScript code. A global ID can be useful to differentiate between multiple instances of a component or for debugging purposes.
A component has two types of IDs: a local ID and a global ID. You can retrieve a component using its local ID in your JavaScript code. A global ID can be useful to differentiate between multiple instances of a component or for debugging purposes.
Local IDs
A local ID is an ID that is only scoped to the component. A local ID is often unique but it’s not required to be unique.
Create a local ID by using the aura:id attribute. For example:
Find the button component by calling cmp.find(“button1”) in your client-side controller, where cmp is a reference to the component containing the button.
A local ID is an ID that is only scoped to the component. A local ID is often unique but it’s not required to be unique.
Create a local ID by using the aura:id attribute. For example:
Find the button component by calling cmp.find(“button1”) in your client-side controller, where cmp is a reference to the component containing the button.
Global IDs
Every component has a unique globalId, which is the generated runtime-unique ID of the component instance. A global ID (1) is not guaranteed to be the same beyond the lifetime of a component, so it should never be relied on. A global ID can be useful to differentiate between multiple instances of a component or for debugging purposes.
Every component has a unique globalId, which is the generated runtime-unique ID of the component instance. A global ID (1) is not guaranteed to be the same beyond the lifetime of a component, so it should never be relied on. A global ID can be useful to differentiate between multiple instances of a component or for debugging purposes.
55. What is a FlexiPage in lightning?
FlexiPage
Represents the metadata associated with a Lightning page. A Lightning page represents a customizable screen made up of regions containing Lightning components.
A Lightning page region can contain upto 25 components.
Represents the metadata associated with a Lightning page. A Lightning page represents a customizable screen made up of regions containing Lightning components.
A Lightning page region can contain upto 25 components.
Lightning pages are referred as FlexiPages in API and referred as Lightning pages elsewhere in SFDC documentation
56. How to make quick lightning action?
Add the force:lightningQuickAction or force:lightningQuickActionWithoutHeader interface to a Lightning component to enable it to be used as a custom action in Lightning Experience or the Salesforce mobile app. You can use components that implement one of these interfaces as object-specific or global actions in both Lightning Experience and the Salesforce app.
57. What are value providers in Salesforce Lightning ?
Value providers helps use to access data in Lightning Application .They are two value providers as v(View) and c(controller)
v is component attribute set which helps to access component attribute values in markup
c is component controller helps us to link with event handlers and action for the component
Value providers helps use to access data in Lightning Application .They are two value providers as v(View) and c(controller)
v is component attribute set which helps to access component attribute values in markup
c is component controller helps us to link with event handlers and action for the component
58. List of Global value providers?
$globalID
$Browser
$Label
$Locale
$Resource
$Browser
$Label
$Locale
$Resource
59. What are list of tools are avaliable in salesforce lightning ?
Lightning Connect
Lightning Component Framework
Lightning Schema Builder
Lightning Process Builder
Lightning App Builder
Lightning Component Framework
Lightning Schema Builder
Lightning Process Builder
Lightning App Builder
The answer to the questions have been referred from https://developer.salesforce.com and are reiterated in my language. Please go to the community to better understand the concept and enhance your knowledge, meanwhile use this post a help during your interview.
Keep learning.
Keep learning.
1. create domain name for your org :
setup
|-----Adminster
|--------Domain Management
|--------------MyDomain
a. Enter Domain Name
b. Check availabilty
c. Register
4. Click on login button to test the connection
5. Deploy to users so that users can login using this domain url
2. create package : This is optional ,but if you want to provide lightning apps to the external system or if you want to provide this lightning application as Appexchange product then Package creation is a must
=============================================================================================================
Lishtning Application
============================================================================================================
1. Steps to create lightning Application
UserName
|----Developer Console
|---File
|-----Lightning App
|---App name
Note : All the lightning applications will have an extention of .app
Ex: <aura:application>
This is a test application
</aura:applicaiton>
2. <aura: applicaiton >
1. Every lightning application will start and end with <aura:applicaiton> component .
Arributes :
a)access : indicates whether this app can be extended by another app outside of a namespace.
possible values : global and public
b)controller: This is will take name of the Apex class whose functionalities are used in this application..
If you create namespace : :namespace.className.
if you dont create namespace : classname
c.extends:name of the app which need to be extended .
d.extensible:Indicates whether this app can be extended by another app.
possible values : true /false
e)implements:It will take the list of interfaces that the application want to implements.
Ex : implements ="one,two,three"
Note : App can implement more than one interface
=============================================================================================================
Component :
=============================================================================================================
1.<aura:component> :
a. Components are the functional units of Aura,
b. These components encapsulate modular and reusable sections of UI.
c. They can contain other components or HTML markup.
Syntax:
<aura:component>
<!-- Optional component attributes here -->
<!-- Optional HTML markup -->
</aura:component>
d.Attributes :
1)access:indicates whether this component can be extended by another app outside of a namespace.
possible values : global and public
2)controller : This is will take name of the Apex class whose functionalities are used in this Component.
If you create namespace : :namespace.className.
if you dont create namespace : classname
3)extends:name of the component which need to be extended .
4)extensible:Indicates whether this componnent can be extended by another component.
possible values : true /false
5)implements: It will take the list of interfaces that the component want to implements.
Ex : implements ="one,two,three"
Note : Componnet can implement more than one interface
e. Steps to create aura: componet
UserName
|------Developer console
|----File
|----Lightning Componet
|--------------Component Name
Example : capital1.cmp
<aura:component >
<h1> This is a line one </h1>
<h2> This is line two</h2>
<h3> This is line three</h3>
</aura:component>
f. How to invoke the component in the application ;
1. if the you have created any namespace then is should be called using namespace
<namespace: componentName >
Ex: if namespace : capitalInfosol
component name is : example1
<capitalinfosol : example1>
2) if you dont have the namespace then it will be called using defualt namespace i.e c
<c: example1>
Example : one .app
<aura:application >
This is a test app
<c:capital1></c:capital1>
</aura:application>
============================================================================================================
Example 1 : Create an application with multiple components
============================================================================================================
a . Create a new component : student
<aura:component >
<h1> Iam new Student </h1>
<div> This is a test component</div>
</aura:component>
b. create a new component studentAddress
<aura:component >
<div>
Ameerpet <br/>
SRNagar <br/>
Hyd <br/>
TG <br/>
</div>
</aura:component>
c. Create new Application : app2
<auar: application >
<c:student />
<c:studentAddress />
</aura:application>
===========================================================================================================
Example 2: Applying CSS on component
===========================================================================================================
1. create a Component : csscomp.cmp
<aura:component >
<h1> This is line one </h1>
<div class="red"> This is red</div>
<div class="green"> This is green</div>
<div class="blue"> This is blue</div>
</aura:component>
2. Style : Click on Style button on the right side wizard
:Then it creates csscomp.css
.THIS {
background-color:yellow;
padding-top : 40px;
padding-left :40px;
}
.THIS.red {
background-color: red;
}
.THIS.blue {
background-color: blue;
}
.THIS.green {
background-color: green;
}
3. Application : capital3
<aura: application>
<c:csscomp> </c:csscomp>
<aura :application>
=====================================================================================================
Creating attributes for a component
===================================================================================================
<aura:attribute>
aura:attribute is used to create an attribute on an app, interface, component, or event.
Attributes :
a) access:Indicates whether the attribute can be used outside of its own namespace.
b) name :Required.The name of the attribute.
c) type :Required. The type of the attribute.
Possible values (Date,DateTime,Decimal,Double,Integer ,Long ,string ,Boolea )
d) defualt: Value that should be assingned to the attribue if no values are assigned to it.
e) description: A summary of the attribute and its usage
f) required : Specified wheather attribute value need to be required to run this component.
Example :
<aura: attribue name="empName" type="String" defualt="capitalinfo" required="true" />
Examples :
<aura:component >
<aura:attribute name="empName" type="string" />
<aura:attribute name="salary" type="Decimal" required="true" />
<aura:attribute name="city" type="string" default="Hyd" />
<aura:attribute name="phones" type="String[]" description="This contains all phone numbers of account" />
</aura:component>
How to read the values of attributes in the component / appliation
1. we get the values of the atrributes using {! v.attributeName}
Ex : {! v.empName }
Ex :{! v.salary}
Ex :{! v.city}
Ex :{! v.phone}
Example : How to pass the values of the component from application .
a. Create a new Component :employee.cmp
<aura:component >
<aura:attribute name="name" type="string" required="true"/>
<aura:attribute name="exp" type="Decimal" />
<aura:attribute name="City" type="String" default="Hyd" />
<div>
Employee Name : {! v.name} <br/>
Employee Exp : {! v.exp} <br/>
Employee City :{! v.city}
</div>
</aura:component>
b. create style for the component : employee.css
.THIS {
padding-top: 40px;
padding-left:80px;
color: blue;
}
c. Create an application : capital.4
<aura:application >
<c:employee name="Satish Myla" exp="3.4" />
</aura:application>
=============================================================================================================
<aura:handler>
a. This component is used to intialize the values /attributes in the component /application
b. This event istriggered on app or component for initialization.
c. This event is automatically fired when an app or component is has initializations prior to rendering. T
Attributes :
a .name : It should be alwasys "init" only
b. value : This should be assined {! this}
c. action :The client-side controller action that handles the value change.
Syntax :
<aura:handler name="init" value="{!this}" action="{!c.functionname} " />
Syntax of controller :
(
{
methodname :function(component)
{
}
})
Q:: How to read the values of attributes with in the controller
component.get("v.attributename");
Q:: How to set the values of attributes with in the controller
component.set("v.attribute" ,value);
============================================================================================================
Example 1:
a. Create a component with three attributes aval,bval,cval
Calculate.cmp
<aura:component >
<aura:attribute name="aval" type="Integer" required="true" />
<aura:attribute name="bval" type="Integer" required="true"/>
<aura:attribute name="cval" type="Integer" />
<aura:handler name="init" value="{!this}" action="{!c.add}" />
<div>
<h2> AVal : {!v.aval}</h2>
<h2>BVal :{!v.bval}</h2>
<h2>CVal :{!v.cval}</h2>
</div>
</aura:component>
b. create style for the component :
.THIS {
padding-left :80px;
padding-top :80px;
color :green;
}
c. create a clientside controller by clicking controller button on right side menu wizard
calculate.js
({
add : function(component) {
var aval=component.get("v.aval");
var bval=component.get("v.bval");
var cval=aval+bval;
component.set("v.cval",cval);
}
})
d. crate new application capital.app
<aura:application >
<c:calculate aval="10" bval="10" />
</aura:application>
Examples 2 :
a. create a new custom component :
empcomp
<aura:component >
<aura:attribute name="empName" type="string" default="Enter Name" />
<aura:handler name="init" value="{!this}" action="{!c.show}" />
Employee Name :{! v.empName}
</aura:component>
b. createa client side Controller:
({
show : function(component) {
component.set(" v.empName "," Satish Myla ");
}
})
c create a Application :
<aura:application >
<c:empcomp> </c:custom1>
</aura:application>
Example 3:
a. create custom component : intrestcalcualte
<aura:component >
<aura:attribute name="empName" type="string" default="Enter Name" />
<aura:attribute name="amount" type="decimal" />
<aura:attribute name="rate" type="integer" />
<aura:attribute name="years" type="integer" />
<aura:attribute name="intrest" type="decimal" />
<aura:handler name="init" value="{!this}" action="{!c.calculate}" />
<div>
Employee Name :{! v.empName} <br/>
Amount : {!v.amount} <br/>
Rate : {!v.rate} <br/>
Years :{! v.years} <br/>
Intrest:{! v.intrest}
</aura:component>
b. create a css style for a component ;
.THIS {
padding-left :80px;
padding-top :80px;
color :green;
}
c. create a clinet side controller
({
calcualte : function(component) {
component.set("v.empName","satish myla");
var amount=component.get("v.amount");
var years=component.get("v.years");
var rate=component.get("v.rate");
var intrest=amount*years*rate/100;
component.set("v.intrest",intrest);
}
})
d. create an application
<aura:application >
<c:intrestcalcualte amount="10000" rate="10" years="2"></c:comp3>
</aura:application>
=============================================================================================================
How to refer to array of elements :
===========================================================================================================
<aura:iteration> :
1. This component is used to display collecton elements by iterating over every element
Attribues :items: Required. The collection of data to iterate over.
var : Required. The variable name to use for each item inside the iteration.
Example 1:
1. create custom component :
collection1:
<aura:component>
<aura:iteration items="1,2,3,4,5" var="item">
<h1>Items : {!item}</h1>
</aura:iteration>
</aura:component>
2. Create a applicaiton : capital6
<aura:application>
<c:collection1 />
</aura:application>
Example 2:
1. create custom component : collection2.cmp
<aura:component >
<aura:attribute name="names" type="string[]" default="['Ram','Ravi','Kiran']" />
<aura:iteration items="{!v.names}" var="s">
<h1> Employee Name :{!s} </h1>
</aura:iteration>
</aura:component>
2. Application :
<aura:application >
<c:collection2></c:collection2>
</aura:application>
Example 3:
1. create a custom component :
<aura:component >
<aura:attribute name="names" type="string[]" />
<aura:handler name="init" value="{!this}" action="{!c.callme}" />
<aura:iteration items="{!v.names}" var="s">
<h1> Employee Name :{!s} </h1>
</aura:iteration>
</aura:component>
2. create custom controller
({
callme : function(component) {
var names=['Ram','Kiran','Hari'];
component.set("v.names",names);
}
})
3. create new Application
<aura:application >
<c:collection3></c:collection3>
</aura:application>
==============================================================================================================
Example : Creating Form using UI components in Lightning
1. create the component to create UI comonents
<aura:component >
<ui:inputNumber label="Amount" placeholder="0" /><br/>
<ui:inputText label="Enter Name" placeholder="FirstName,Last" /><br/>
<ui:inputCurrency label="Salary " /> <br/>
<ui:inputDateTime label="Date" displayDatePicker="true"/>
<ui:button label="Submit" />
</aura:component>
2. create a application
<aura:application >
<c:uicomponent1 />
</aura:application>
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Q:: Setting and getting values of component using id in the controller method
component.find("idname").get("v.value");
component.find("idname").set("v.value",value);
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Example 1:
1. create a component :uicomponent2
<aura:component >
<ui:inputText label="Enter Name" placeHolder="Employee Name" aura:id="name" />
<ui:inputText label="My Name " aura:id="myname" />
<ui:button label="submit" press="{!c.callme}" />
</aura:component>
2. create a controller :
({
callme : function(component) {
var name=component.find("name").get("v.value");
component.find("myname").set("v.value",name);
}
})
3. Create a application :
<aura:application >
<c:uicomponent2 />
</aura:application>
Example 2 :
<aura:component >
<ui:inputText label="Name" aura:id="name" placeholder="First, Last"/>
<ui:button aura:id="outputButton" label="Submit" press="{!c.getInput}"/>
<ui:outputText aura:id="nameOutput" value=""/>
</aura:component>
Controller :
({
getInput : function(cmp, event) {
var fullName = cmp.find("name").get("v.value");
var outName = cmp.find("nameOutput");
outName.set("v.value", fullName);
}
})
Application :
<aura:application >
<c:comp5></c:comp5>
</aura:application>
=============================================================================================
Example 9 :set the attribute values from the UI components based on the events on componets
<aura:component >
<aura:attribute name="first" type="String" default="John"/>
<aura:attribute name="last" type="String" default="Doe"/>
<ui:inputText label="First Name" value="{!v.first}" updateOn="keyup"/>
<ui:inputText label="Last Name" value="{!v.last}" updateOn="keyup"/>
<!-- Returns "John Doe" -->
<ui:outputText value="{!v.first +' '+ v.last}"/>
</aura:component>
Application :
<aura:application >
<c:comp6></c:comp6>
</aura:application>
==========================================================================================
Example 10:Creating a picklist component
<aura:component >
<ui:inputSelect>
<ui:inputSelectOption text="Red"/>
<ui:inputSelectOption text="Green" value="true"/>
<ui:inputSelectOption text="Blue"/>
</ui:inputSelect>
</aura:component>
Application :
<aura:application>
<c:compPick></c:compPick>
</aura:application>
============================================================================================
Example 12: If Else in the lightning
<aura:component >
<aura:attribute name="edit" type="Boolean" default="true"/>
<aura:if isTrue="{!v.edit}">
<ui:button label="Edit"/>
<aura:set attribute="else">
No button
</aura:set>
</aura:if>
</aura:component>
Application :
<aura:application>
<c:comp8></c:comp8>
</aura:application>
==========================================================================================
Reading the data from the Apex Class:
1. Every method of the apex which we want to invoke in the lightning should obey the following rules
a . Method should be annotated with @AuraEnabled
b. Method should be static method
c. Method should have returnType to pass the data
2. If you want to the apex class in the lightning component / application it should be define as a controller
3.When we want to invoke the reffer to the server-side controller method from the client side controller
method
Syntax :
component.get("c.methodName");
4. When want to the setCallback of to the controller
var mycall=component.get("c.methodName");
myCall.setcallback(this, function(response) {
logic
});
5.When the method gives the reponse check the status
var state=response.getStatus();
6.Every apex method invocation from the controller javascript is asynchronous so we need to
enqueu the job;
$A.enqueueAction(action);
Example :
1. Create a apex class with aura enabled methods
Apex class : AuraExample1
public class AuraExample1 {
@AuraEnabled
public Static String getName(){
return 'Satish Myla';
}
}
2. create a custom Componet which invokes the apex class
<aura:component controller="AuraExample1">
<aura:attribute name="empName" type="string" />
<ui:button label="Get EmpData" press="{!c.show}"/>
<h1>Employee Name :{! v.empName} </h1>
</aura:component>
3. create a client side controller
({
show : function(component) {
var action=component.get("c.getName");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
component.set("v.empName", response.getReturnValue());
}
});
$A.enqueueAction(action);
}
})
4. create a application
<aura:application >
<c:apexcall />
</aura:application>
===============================================================================================
Example 14: Reading a list account records from Sobject and display in Lightning
Apex class : AuraExample2:
public class AuraExample2 {
@AuraEnabled
public Static Account[] getAccounts(){
List<Account> accs=[select id,name from Account limit 4];
return accs;
}
}
Component : Custom5 :
<aura:component controller="AuraExample2">
<aura:attribute name="Accounts" type="Account[]" />
<ui:button label="Get Accounts" press="{!c.getAccs}"/>
<aura:iteration var="a" items="{!v.Accounts}">
<p>{!a.Name} : {!a.Id}</p>
</aura:iteration>
</aura:component>
Controller:
({
getAccs: function(cmp){
var action = cmp.get("c.getAccounts");
action.setCallback(this, function(response){
var state = response.getState();
if (state === "SUCCESS") {
cmp.set("v.Accounts", response.getReturnValue());
}
});
$A.enqueueAction(action);
}
})
Application :
<aura:application >
<c:custom5></c:custom5>
</aura:application>
==============================================================================================
Example 15 :Setting the body part of the component
-------------------------------------------------------------------
<aura:component>
<aura:set attribute="body">
<!--START BODY-->
<div>Body part</div>
<ui:button label="Push Me"/>
<!--END BODY-->
</aura:set>
</aura:component>
App6.app
<aura:application >
<c:bodyAttribute></c:bodyAttribute>
</aura:application>
-------------------------------------------------------------------------
Example 16: Component Facets
-------------------------------------------------------------------------
facetHeader.cmp
<aura:component>
<aura:attribute name="header" type="Aura.Component[]"/>
<div>
<span class="header">{!v.header}</span><br/>
<span class="body">{!v.body}</span>
</div>
</aura:component>
facetHeaders.cmp
<aura:component>
See how we set the header facet.<br/>
<c:facetHeader>
Nice body!
<aura:set attribute="header">
Hello Header!
</aura:set>
</c:facetHeader>
</aura:component>
Application
<aura:application >
<c:facetHeaders></c:facetHeaders>
</aura:application>
========================================================================================
Example 17 : Adding lightning application in vf page
<aura:application access="GLOBAL" extends="ltng:outApp">
<aura:dependency resource="ui:button"/>
</aura:application>
VF Page :
<apex:page>
<apex:includeLightning />
<div id="lightning" />
<script>
$Lightning.use("c:app15", function() {
$Lightning.createComponent("ui:button",{ label : "Press Me!" },
"lightning",function(cmp) {});
});
</script>
</apex:page>
==================================================================
How to call one controller function from another controller function in Lightning?
<aura:method name="barMethod" action="{!c.bar}"
description="bar controller function" />
Then you can reference it on the controller:
({
bar : function(component, event, helper) {
// Do something cool
},
foo : function(component, event, helper) {
// This is how you call bar() from here
component.barMethod();
}
})
====================================================================================
Lightning Component JS controller call one method from other methods without helper [duplicate]
selectOther: function(component, event, helper) {
var fethAddress = component.get('c.fetchAddress');
$A.enqueueAction(fethAddress);
},
fetchAddress: function(component, event, helper) {
console.log('---fetchAddress');
}
====================================================================
call other methods of helper from the helper. To call other helper methods, you will have to use this keyword
ExampleController.js :
onValueChange : function(component, event, helper){
helper.callMethodOne(component, event);
}
ExampleHelper.js :
callMethodOne : function(component, event){
this.callMethodTwo(component, event);
},
callMethodTwo : function(component, event){
console.log("calling callMethodTwo");
// Your re-usable code inside the related Component.
}
===================================================================
If you want to call a function from another function you will need to have the two functions defined in your lightning helper rather than the lighting controller. You can then call
bar : function(component, event, helper) {
console.log('bar just happened');
},
foo : function(component, event, helper) {
this.bar(component, event, helper);
}
=====================================================================
=====================================================================
Salesforce Lightning Component Framework has provided us four phases of Rendering.
Lightning Component lifecycle
A basic understanding of the sequence of steps that takes place when a Lightning Component communicates with a client and a server will help a great deal before we dive deep into how to build a Lightning Component.
The following diagram shows how a Lightning Component works between the client and server:

The key things to note from the previous diagram are as follows:
- A user action instantiates the component and an init event is raised
- The JavaScript controller function calls the helper function to perform any server-side action
- The Apex controller method is invoked from the helper function, the data is returned, ...
Diagram of Rendering Lifecycle
We have to create three lightning components to learning this article.
- defaultLightningPanel
- showContacts [In this learning, we will not describe how to write “showContacts” component. You can write this Lightning Component using lightning:dataTable]
- renderingLifecycle
Difference between Local Id and Global Id
What is bound{! } expression and unbound{# } expression?
Bound Expression: {!v.attributeName}: Anything has been changed to the attribute in the Child Component affects the respective attribute in the Parent Component and vice-versa.
Unbound Expression: {#v.attributeName}: Anything has been changed to the attribute in the Child Component doesn’t affect the respective attribute in the Parent Component and vice-versa.
Unbound Expression: {#v.attributeName}: Anything has been changed to the attribute in the Child Component doesn’t affect the respective attribute in the Parent Component and vice-versa.
Following diagram depicts the use case of Bound Expression and Unbound Expression.
- Use Storable Action. ...
- Use Lightning Data Service. ...
- Custom Cache. ...
- Lazy Instantiation of Component. ...
- Conditional rendering. ...
- Use of Unbound Expression. ...
- Use aura:method for Component Communications. ...
- Limit event handlers.
Thanks & Regards
Rehan Ahmad Khan
Comments
Post a Comment