Tag: Lightning Component

Configure Lightning Components for Community Builder

We will see here how to add the custom lightning component on to the community builder. To appear as a drag-and-drop component in Community Builder, a component must implement the forceCommunity:availableForAllPageTypes interface. After you create the Lightning component, it appears in the Components panel of all Lightning communities in your Org..

1.Create a Component 

Here’s the sample code for the custom component that will be used in the community builder.

Apex Class

Component (FirstCommunityCmp.cmp)

Styles

 

  • To make a resource, such as a component, usable outside of your own org, mark it with access=” global”.
  • When you add custom components to your community, they can bypass the object- and field-level security (FLS) you
    set for the guest user profile.
  • Lightning components don’t automatically enforce CRUD and FLS when referencing objects or retrieving the objects from an Apex controller. This means that the framework continues to display records and fields
  • You must manually enforce CRUD and FLS in your Apex controllers.

2. Add a Design Resource to  Component Bundle

A design resource controls which component attributes are exposed in Community Builder. The design resource lives in the same folder as your .cmp resource and describes the design-time behavior of the Lightning component—information that visual tools need to display the component in a page or app.

Here is the designer code

3. Add an SVG Resource to Component 

To define a custom icon for your component, add an SVG resource to the component bundle. The icon appears next to the component in the Community Builder Components panel. Here is the code for SVG

4. Drag and Drop the component to Community 

Now go the Salesforce community builder and drag and drop the component as shown below.

Configure the component attribute as shown below and publish your changes

After publishing the community you can able to see the basic information of the user as shown below.

 

lightning:datatable inline editing

A lightning:datatable component displays tabular data where each column can be displayed based on the data type . in this post, we will see how to use the data table inline edit the cells. you can make data table columns as editable by passing editable to true at the column level. When you make a column editable, a pencil icon appears when you hover over the cells in that column. Clicking the icon or pressing the Enter key triggers inline editing. Inline editing is not supported for date and location fields. The datatable supports mass inline editing, so you can edit content in multiple table cells and save the changes in one step. The component verifies that you want to update multiple items before it applies your changes. Make a column editable by setting editable to true when you are defining your columns in the controller.

The final data table looks as shown below.

 

Apex Class 

The above apex class is used to update the inline edit data and used to get all the accounts to show in the table.

Lightning Component 

Controller.js

helper.js

 

Understing code 

1. Cells in datatable are editable only if you set the editable property to true at the column level. In the below controller code we are setting the field columns that are editable.

 

2. In the component markup data table, we need to use the draft value attributes and onsave action to save the edit the cells.

3.You can handle the oncancel, oncellchange, and onsave actions when the cell value changes or is saved. When the onsave action is used, the Cancel and Save button appears after a value cell changes and you press the Enter or Tab key, or move away from the cell.  Retrieve the new value using event.getParam('draftValues').

above code with retrieve the new values from the edited cells and passing to the apex controller to save the data into the Salesforce object. once status is the success it will refresh the screen.

Using Promise In Lightning Component

Introduction 

In this blog, I am going to explain how to use Promise in the lightning component. Salesforce lightning components had improved performance by its asynchronous nature itself by managing the lifecycle. Promises are one of the ways to deal with asynchronous code in JavaScript without writing callbacks. A promise is commonly defined as a proxy for a value that will eventually become available. For example, if you use the promise API to make an asynchronous call to a web service, you will create a Promise object which represents the data that will be returned by the web service in future. The caveat is that the actual data isn’t available yet. It will become available when the request completes and a response comes back from the web service. In the meantime, the Promise object acts as a proxy to the actual data. Furthermore, you can attach callbacks to the Promise object, which will be called once the actual data is available.

How Promises Work

The promise is asynchronous so when Promise is executed it contains different status. When a promise is pending, it can transition to the fulfilled or rejected state. Once a promise is fulfilled or rejected, however, it will never transition to any other state, and its value or failure reason will not change. A promise can be in one of 3 states:

  • Pending – the promise’s outcome hasn’t yet been determined
  • Fulfilled – the asynchronous operation has completed
  • Rejected – the asynchronous operation failed.

Create a Promise

The Promise object is created using the new keyword and its constructor. This constructor takes as its argument a function, called the “executor function”. This function should take two functions as parameters. The first of these functions (resolve) is called when the asynchronous task completes successfully and returns the results of the task as a value. The second (reject) is called when the task fails and returns the reason for failure, which is typically an error object The promise syntax looks like as shown below.

To provide a function with promise, simply have it return a promise. The following serverSideCall function is returning the Promise object. Once the promise object returns the success response, it will invoke the resolve otherwise it will invoke reject.

Now all the functions get the promise object instance.

after creating the promise object instance you need to call the then() method. All promise instances get a then method which allows you to react to the promise.

 Or simply

Chaining Promises

When you need to coordinate or chain together multiple callbacks, promises can be useful. The generic pattern is:

Orchestrating promises

If you need to synchronize different promises, Promise.all() helps you define a list of promises, and execute something when they are all resolved.

Promise.race()

Use of Promise.race Instead of waiting for all promises to be resolved or rejected, Promise.race triggers as soon as any promise in the array is resolved or rejected

 

Handling Errors

What if an error occurs while performing an asynchronous operation?  In synchronous code, you can use try/catch, and rely on exception propagation to errors handle. The Promises API includes a catch() method to optionally catch unhandled errors. Always include a reject handler or a catch() method in your promise chain. Throwing an error in a promise doesn’t trigger window.onerror, which is where the framework configures its global error handler. If you don’t have a catch() method, keep an eye on your browser’s console during development for reports about uncaught errors in a promise. To show an error message in a catch() method, use $A.reportError().

 

Time to code 

Here is the complete code that will demonstrate different ways of promise usage

Apex Class

 

 

Lightning Component

controller

 

helper

 

 

 

Usage Of lightning:datatable

Introduction

In this blog, I am going to explain how to use salesforce lightning:datatable component and its features. A lightning:datatable component displays tabular data where each column can be displayed based on the data type .lightning:datatable is not supported on mobile devices. Inline editing is currently not supported. Supported features include

  • Displaying and formatting of columns with appropriate data types
  • Infinite scrolling of rows
  • Header-level actions
  • Row-level actions
  • Resizing of columns
  • Selecting of rows
  • Sorting of columns by ascending and descending order
  • Text wrapping and clipping

Tables can be populated during initialization using the data, columns, and keyField attributes.The table data is loaded using the init handler. Selecting the checkbox enables you to select the entire row of data and triggers the onrowselection event handler. The below code shows how to use the lightning: datatable to initialize the data and columns which are passed by using attributes.

Here’s the client-side controller that creates the column’s object to their corresponding column data.

The below code used to set the data for the data table.

 Using an Apex Controller

Let’s say you want to display data in the Book object. Create an Apex controller that queries the fields you want to display.This apex controller is having different methods that are used in other data table features like total rows and infinite loading and row, header actions.


 

Infinite Scrolling to Load More Rows

Infinite scrolling enables you to load a subset of data and then display more when users scroll to the end of the table. To enable infinite scrolling, set enableInfiniteLoading to true and provide an event handler using onloadmore. By default, data loading is triggered when you scroll down to 20px from the bottom of the table, but the offset can be changed using the loadMoreOffset attribute. Here is the list of attributes need to set for lightning:datatable for enabling the infinity loading.

Here is the below controller logic

 

Header-Level Actions

Header-level actions refer to tasks you can perform on a column of data, such as displaying only rows that meet a criterion provided by the column. You can perform actions on a column and handle them using the onheaderaction event handler.Here is the markup which needs to set while initializing the data table on init.

 

Below is the controller action that used to handler the header action based on used is selected what type of data user wanted to see like completed or pre-order or in completed books based on the status.

 

Static Row-Level Actions

Row-level actions refer to tasks you can perform on a row of data, such as updating or deleting the row. Static actions apply to all rows on the table. You can perform actions on each row and handle them using the onrowaction event handler.

You must provide a list of actions to the data of the column, which can be done during initialization. This client-side controller initializes the actions column and handles the actions on each row, displaying the row details and deleting the row when the action is clicked.

 

Sorting Data By Column

To enable sorting of row data by a column label, set sortable to true for the column on which you want to enable sorting. Set sortedBy to match the fieldName property on the column. Clicking a column header sorts rows by ascending order unless the defaultSortDirection is changed, and clicking it subsequently reverses the order. Handle the onsort event handler to update the table with the new column index and sort direction.

 

Below controller and helper code show sorting logics from the component controller.

Handling Selected  Rows 

The selectedRows attribute enables programmatic selection of rows, which is useful when you want to preselect rows.If maxRowSelection is set to a value less than the number of selected rows, only the specified number of rows will be selected.

Complete code is here

 

Controller code

 

helper