March 26, 2020

How to iterate over Records returned By Wire Service in LWC

Sample Code:

HTML:

<template>

    <div> 

        <lightning-datatable key-field="Id"
                             data={accountsWithIndustry}
                             columns={columns}
                             hide-checkbox-column="true" 
                             show-row-number-column="true">
        </lightning-datatable>

    </div>    
    <div> 

        <lightning-datatable key-field="Id"
                             data={accountsWithoutIndustry}
                             columns={columns}
                             hide-checkbox-column="true" 
                             show-row-number-column="true">
        </lightning-datatable>

    </div>       
   
</template>


JavaScript:

import { LightningElement, wire, track } from 'lwc';
import fetchAccounts from '@salesforce/apex/ExampleController.fetchAccounts';

const columns = [ 
    { label: 'Name', fieldName: 'Name' }, 
    { label: 'Industry', fieldName: 'Industry' }, 
];

export default class Example extends LightningElement {

    @track accountsWithIndustry;
    @track accountsWithoutIndustry;
    @track columns = columns;

    @wire(fetchAccounts)
    accountData({ error, data }) {

        if ( data ) {
           
            var tempAccountsWithIndustry = [];
            var tempAccountsWithoutIndustry = [];

            for ( var i = 0; i < data.length; i++ ) {

                if ( data[ i ].Industry )
                    tempAccountsWithIndustry.push( data[ i ] );
                else
                    tempAccountsWithoutIndustry.push( data[ i ] );

            }

            this.accountsWithoutIndustry = tempAccountsWithoutIndustry;
            this.accountsWithIndustry = tempAccountsWithIndustry;
            console.log( JSON.stringify( this.accountsWithIndustry ) );
            console.log( JSON.stringify( this.accountsWithoutIndustry ) );

        }
   
   
    }

}


JavaScript-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>     
    <targets>   
        <target>lightning__Tab</target>   
    </targets>
</LightningComponentBundle>


Apex Class:

public with sharing class ExampleController {

    @AuraEnabled(cacheable=true)
    public static List < Account > fetchAccounts() {

        return [ SELECT Id, Name, Industry FROM Account LIMIT 10 ];
       
    }
   
}


Output:


How to use Omni-Channel for LiveMessage in Salesforce Classic?

1. Enable Omni-Channel from Setup.

2. Create a Service Channel.






3. Create a Routing Configuration.


4. Create a Queue with above Routing Configuration. Select LiveMessage Session for Selected Objects.


5. Create a Presence Status with LiveMessage selected in the Service Channels.


6. Add the Presence Status to the Enabled Service Presence Status Access under your profile for testing.


7. Enable ITR Enabled and select the Queue created for LiveMessage


8. Add Omni-Channel and Live_TextPanel_Hidden to Console Components for the LiveMessage App.


9. Go to LiveMessage App and select Available - LiveMessage to start accepting the messages.


March 24, 2020

lightning-tree-grid with Collapse All and Expand All using LWC in Salesforce

Sample Code:

HTML:

<template>

    <div class="slds-p-around_medium lgc-bg">

        <div class="slds-m-bottom_small">

            <lightning-button
                label="Collapse All"
                onclick={clickToCollapseAll}>
            </lightning-button>
            <lightning-button
                label="Expand All"
                onclick={clickToExpandAll}>
            </lightning-button>
           
        </div>
       
        <lightning-tree-grid columns = {gridColumns}
                                data = {gridData}
                                key-field = "Id"
                                hide-checkbox-column = true>
        </lightning-tree-grid>

    </div>
   
</template>


JavaScript:

 import { LightningElement, track, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/ExampleController.fetchAccounts';

export default class Example extends LightningElement {

    @track gridColumns = [{
        type: 'text',
        fieldName: 'Name',
        label: 'Name'
    },
    {
        type: 'text',
        fieldName: 'Industry',
        label: 'Industry'
    },
    {
        type: 'text',
        fieldName: 'FirstName',
        label: 'FirstName'
    },
    {
        type: 'text',
        fieldName: 'LastName',
        label: 'LastName'
    }];
    @track gridData;

    @wire(fetchAccounts)
    accountTreeData({ error, data }) {

        console.log( 'Inside wire' );
        if ( data ) {

            var tempData = JSON.parse( JSON.stringify( data ) );
            console.log( 'Data is ' + tempData );
            /*var tempjson = JSON.parse( JSON.stringify( data ).split( 'Contacts' ).join( '_children' ) );
            console.log( 'Temp JSON is ' + tempjson );*/
            for ( var i = 0; i < tempData.length; i++ ) {

                tempData[ i ]._children = tempData[ i ][ 'Contacts' ];
                delete tempData[ i ].Contacts;

            }
            this.gridData = tempData;

        } else if ( error ) {
          
            if ( Array.isArray( error.body ) )
                console.log( 'Error is ' + error.body.map( e => e.message ).join( ', ' ) );
            else if ( typeof error.body.message === 'string' )
                console.log( 'Error is ' + error.body.message );

        }

    }

    clickToExpandAll( e ) {
        const grid =  this.template.querySelector( 'lightning-tree-grid' );
        grid.expandAll();
    }

    clickToCollapseAll( e ) {

        const grid =  this.template.querySelector( 'lightning-tree-grid' );
        grid.collapseAll();
      
    }

}


Apex Class: 

public with sharing class ExampleController {

    @AuraEnabled(cacheable=true)
    public static List < Account > fetchAccounts() {

        return [ SELECT Id, Name, Industry, ( SELECT Id, FirstName, LastName FROM Contacts ) FROM Account LIMIT 10 ];
       
    }
   
}



Output:


March 23, 2020

Creating Public Link from Salesforce File - Share Files to Public from Salesforce Files

1. Open the file.

2. Click Public Link and get the generated URL to share the file.


PopUp using Lightning Web Component LWC

HTML:

<template>

    <lightning-button onclick={showPopUp} label="Show PopUp"></lightning-button>

    <div class="demo-only" style="height: 640px;" if:true={checkBool}> 
 
        <section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true" aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open"> 

            <div class="slds-modal__container"> 

                <header class="slds-modal__header"> 

                    <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={closeModal}> 
                        <lightning-icon icon-name="utility:close" size="medium"> 
                        </lightning-icon> 
                        <span class="slds-assistive-text">Close</span> 
                    </button> 
                    <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">Sample Header Information</h2> 

                </header> 

                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">                             

                        Test Body Information
                         
                </div> 

                <footer class="slds-modal__footer"> 
                    <center><h1 style="color:green;">Footer Information</h1></center> 
                </footer> 

            </div> 

        </section> 

        <div class="slds-backdrop slds-backdrop_open"></div> 
    </div> 
   
</template>


JavaScript:

import { LightningElement, track } from 'lwc';

export default class Example extends LightningElement {

    @track checkBool = false;

    showPopUp(){

        this.checkBool = true;
       
    }

    closeModal() { 
 
        this.checkBool = false; 
 
    }

}


JavaScript-meta.xml:(For using the LWC as a Tab)

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>     
    <targets>   
        <target>lightning__Tab</target>   
    </targets>
</LightningComponentBundle>


Output:


March 22, 2020

End users adding and removing Tabs from Salesforce Apps

Admins can set Default On, Default Off and Tab Hidden.

End users can personalise the below actions on Tabs in Navigation Bar

1. ReOrder
2. Add
3. Remove


To Reset, use the Reset Navigation to Default.

Reference Link

https://help.salesforce.com/articleView?id=user_userdisplay_tabs_lex.htm&type=5

When creating a tab, use "Append tab to users' existing personal customizations", to override the user's customization.


March 19, 2020

lightning-tree-grid with Account and its related Contacts using LWC in Salesforce

Sample Code:

HTML:

 <template>
  
    <div class="slds-p-around_medium lgc-bg">
        <lightning-tree-grid columns = {gridColumns}
                             data = {gridData}
                             key-field = "Id"
                             hide-checkbox-column = true>
        </lightning-tree-grid>
    </div>
  
</template>


JavaScript:

import { LightningElement, track, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/ExampleController.fetchAccounts';

export default class Example extends LightningElement {

    @track gridColumns = [{
        type: 'text',
        fieldName: 'Name',
        label: 'Name'
    },
    {
        type: 'text',
        fieldName: 'Industry',
        label: 'Industry'
    },
    {
        type: 'text',
        fieldName: 'FirstName',
        label: 'FirstName'
    },
    {
        type: 'text',
        fieldName: 'LastName',
        label: 'LastName'
    }];
    @track gridData;

    @wire(fetchAccounts)
    accountTreeData({ error, data }) {

        console.log( 'Inside wire' );
        if ( data ) {

            var tempData = JSON.parse( JSON.stringify( data ) );
            console.log( 'Data is ' + tempData );
            /*var tempjson = JSON.parse( JSON.stringify( data ).split( 'Contacts' ).join( '_children' ) );
            console.log( 'Temp JSON is ' + tempjson );*/
            for ( var i = 0; i < tempData.length; i++ ) {

                tempData[ i ]._children = tempData[ i ][ 'Contacts' ];
                delete tempData[ i ].Contacts;

            }
            this.gridData = tempData;

        } else if ( error ) {
           
            if ( Array.isArray( error.body ) )
                console.log( 'Error is ' + error.body.map( e => e.message ).join( ', ' ) );
            else if ( typeof error.body.message === 'string' )
                console.log( 'Error is ' + error.body.message );

        }

    }

}


Apex Class:

public with sharing class ExampleController {

    @AuraEnabled(cacheable=true)
    public static List < Account > fetchAccounts() {

        return [ SELECT Id, Name, Industry, ( SELECT Id, FirstName, LastName FROM Contacts ) FROM Account LIMIT 10 ];
       
    }
   
}
 


Output:


March 18, 2020

Approval submission and recall using apex in Salesforce with test class

Sample Apex Class:

public class ApprovalProcessController {

    public static Approval.ProcessResult submitForApproval( Id recordId ) {
   
        Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
        req1.setComments( 'Submitting request for approval' );
        req1.setObjectId( recordId );
        Approval.ProcessResult result = Approval.process( req1 );
        return result;

    }

    public static Approval.ProcessResult recallApproval( Id recordId ) {
   
        ProcessInstanceWorkitem[] workItems = [ SELECT Id
                                                FROM ProcessInstanceWorkitem
                                                WHERE ProcessInstance.TargetObjectId =: recordId
                                                AND ProcessInstance.Status = 'Pending' ];
        Approval.ProcessWorkitemRequest pwr = new Approval.ProcessWorkitemRequest(); 
        pwr.setAction( 'Removed' );
        pwr.setWorkItemId( workItems[0].id );       
        Approval.ProcessResult result = Approval.process( pwr );
        return result;
       
    }
   
}


Sample Apex Test Class:

@isTest
private class ApprovalProcessControllerTest {

    static testMethod void testApproval() {
   
        Opportunity opp = new Opportunity( Name = 'Test', CloseDate = System.Today().addDays( 3 ) );
        opp.StageName = 'Prospecting';
        opp.OwnerId = '0056g000003zzqiAAA';
        insert opp;       
        Approval.ProcessResult result = ApprovalProcessController.submitForApproval( opp.Id );
        System.assert( result.isSuccess() );       
        System.assertEquals( 'Pending', result.getInstanceStatus() );   
        result = ApprovalProcessController.recallApproval( opp.Id );
        System.assert( result.isSuccess() );       
        System.assertEquals( 'Removed', result.getInstanceStatus() );       
       
    }

}

March 17, 2020

String Split method in Apex in Salesforce

Sample Code:

String str = 'abc-xyz-123';
List < String > strList = str.split( '-' );
System.debug( 'List String is ' + strList );


Output:


March 16, 2020

Salesforce Interview Questions with Answers Part 62

1. What is Salesforce SOS?What is Salesforce SOS?
System of systems (SOS)

 Add SOS to your native Android or iOS mobile app so that your customers can connect with agents via two-way video or screen sharing.
 SOS is part of Service Cloud Snap-ins for Mobile Apps.

 Agents can access cases, account records, and customer information quickly and easily during their video calls. Agents can also draw on customers’ screens during an SOS session, giving your customers in-app guidance to solve their problems. Your customers get a comprehensive, personal support experience, and your agents have the information they need in the console to solve customer issues.

2. CORS (Cross-origin resource sharing) in Salesforce
Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

To allow client applications running in a web browser to access Salesforce information, you need to register the origin first. On your Salesforce ORG, go to Setup -> Security -> CORS. Include all the domains that need to access Salesforce resources through a web browser.

Salesforce will return the origin in the "Access-Control-Allow-Origin HTTP" header, along with any additional CORS HTTP headers, hence the browser will allow the request.

These Salesforce technologies support CORS.
Analytics REST API
Bulk API
Chatter REST API
Salesforce IoT REST API
Lightning Out
REST API
User Interface API
Apex REST

https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/extend_code_cors.htm

3. Einstein Bots
Dialog
Dialogs are conversation snippets that control what your bot can do.

Intent    
Intents are the customer's reasons for interacting with your bot.

Entity    
An entity represents a type of data that you want to collect from a customer.
Text, DateTime, Date, Money, Number, Person, Location, Organization, Percent, Boolean,
and Object (standard Salesforce or custom)

Variable    
A variable is a container that stores a specific piece of data collected from the customer or output from Salesforce.
The following types are available for custom variables.
Text
Number
Boolean
Object
Date
DateTime
Currency
Id

Add a Bot Profile
Expand a bot’s capabilities and give it access to features like Field Service Lightning by assigning it a custom profile.
Each bot has a Basic Chatbot User profile, but you can create a custom profile and add it to a bot.

Message
Send an outgoing message from your bot to your customer.
A message can be static text or dynamic text from merge fields.
The merge fields reference objects and fields that are currently stored in your bot variables.
The merge field syntax is: {$API_VariableName} or {$API_VariableName.Field}.
Merge context and system variables into bot messages with merge syntax.
{!$System.LastCustomerInput}
{!$Context.ContactId}
{!VariableName}

Question
Gather information from your customer.

Action
Run an autolaunched flow, send email, or use Apex to read, update, or delete Salesforce objects, retrieve data
and display it to the customer, and retrieve external data from a third-party API.

Rules
Specify the conditions that start any of the following actions: call a dialog from within the current dialog,
redirect to a different dialog, clear a variable value, transfer to an agent, and set variables.

Transfer Bot Conversations
1. Use the Transfer to Agent System Dialog to Transfer Conversations.
Transfer conversations to an agent in the queue attached to the Chat deployment defined on the Transfer to Agent dialog.
2. Use the Dialog Rule Element to Transfer Conversations.
a. Transfer Bot Conversations to a Queue
You can route bot conversations to a queue of agents by using the Rule Action Dialog Step.
And, you can help customers who initiates a transfer when agents are offline with the No Available Agents dialog .
b. Transfer Bot Conversations to Another Bot
Create custom solutions in your org by adopting a multi-bot strategy.
Use the Dialog Rule Element to transfer bot conversations to another bot.

4.  AuraEnabled Annotation in Salesforce
The @AuraEnabled annotation enables client- and server-side access to an Apex controller method. Providing this annotation makes your methods available to your Lightning components (both Lightning web components and Aura components). Only methods with this annotation are exposed.

Passing Data to an Apex Controller

Use action.setParams() in JavaScript to set data to pass to an Apex controller.
The request payload includes the action data serialized into JSON.

Returning Data from an Apex Server-Side Controller
Return results from a server-side controller to a client-side controller using the return statement. Results data must be serializable into JSON format.
When an instance of an Apex class is returned from a server-side action, the instance is serialized to JSON by the framework.

5. slideName in Salesforce e.force:navigateToSObject event

The record view contains slides that display the Chatter feed, the record details, and related information. This example displays the related information slide of a record view for the specified record ID.

You can set a specific slide in the Salesforce app, but not in Lightning Experience.

createRecord : function (component, event, helper) {
    var navEvt = $A.get("e.force:navigateToSObject");
    navEvt.setParams({
      "recordId": "00QB0000000ybNX",
      "slideDevName": "related"
    });
    navEvt.fire();
}


In the Salesforce app, you can specify the slide within the record view to display initially. The following slide names are supported.

detail: The record detail slide. This is the default value.
chatter: The Chatter slide.
related: The related information slide.

6. Role Hierarchy in Community Cloud
Role Hierarchy can be set using "Number of partner roles" under Community Settings.Note: Maximum Number of partner roles can be set to 3. Executive, Manager and Worker roles.

7. External Account Hierarchy in Salesforce Community
Now users with Partner Community and Customer Community Plus licenses can view the records of other external users within their account hierarchy. External account hierarchies take the complexity out of sharing data with external users.

Role Hierarchy can be set using "Number of partner roles" under Community Settings.
Note: Maximum Number of partner roles can be set to 3. Executive, Manager and Worker roles.
With External Account Hierarchy, this will change. Check the difference below

Without External Account Hierarchy:
Worker reports to Manager.
Manager reports to Executive.
Executive reports to Account Owner(Internal User) role.

With External Account Hierarchy:
Worker reports to Manager.
Manager reports to Executive.
Executive reports to
1. To account owner(internal user) role if the account doesn't have parent account.
2. To Parent account's highest role(Executive if 3 roles are set in Community Settings, Manager if 2 and Worker if 1).

Note:
1. Account merge is blocked for accounts participating EAHs.
2. Person Account is not supported.

8. How to call a method at regular interval using Aura Components in Salesforce?
$A.getCallback() can be used.
Use $A.getCallback() to wrap any code that modifies a component outside the normal rerendering lifecycle, such as in a setTimeout() call. The $A.getCallback() call ensures that the framework rerenders the modified component and processes any enqueued actions.

https://www.infallibletechie.com/2018/04/agetcallback-usage-for-polling-in.html

9. Run Code When a Component Renders in LWC
The renderedCallback() is unique to Lightning Web Components. Use it to perform logic after a component has finished the rendering phase.

This hook flows from child to parent.

When a component renders, the expressions used in the template are reevaluated.

10. Run Code When a Component Is Inserted or Removed from the DOM in LWC
The connectedCallback() lifecycle hook fires when a component is inserted into the DOM. The disconnectedCallback() lifecycle hook fires when a component is removed from the DOM.

11. Handle Component Errors in LWC
The errorCallback() is unique to Lightning Web Components. Implement it to create an error boundary component that captures errors in all the descendent components in its tree during one of their lifecycle hooks. You can code the error boundary component to log stack information and render an alternative view to tell users what happened and what to do next.

You can create an error boundary component and reuse it throughout an app. It’s up to you where to define those error boundaries. You can wrap the entire app, or every individual component. Most likely, your architecture will fall somewhere in between. A good rule of thumb is to think about where you’d like to tell users that something went wrong.

12. Next Automated Approver Determined By in Salesforce Approval Process
A hierarchy field(Lookup to user object) can be used here.

When a hierarchical field is selected, the same field will be available as an assigned approver option in approval steps.
Automatically assign using the user field selected earlier will be available in the Approval Step.


 

If a hierarchy field is selected, Use Approver Field of Object Owner check box will be available. If this check box is enabled, the approval will go the record owner's hierarchical field instead of the user who is submitting the record for approval.

Example:

UserA's manager is UserB.
UserX's manager is UserY.
Next Automated Approver Determined By is set to manager.
Opportunity Owner is UserA.

If Use Approver Field of Opportunity Owner is enabled,
1. If UserA submits the record for approval, it will go to UserB for approval since Opportunity owner is UserA.
2. If UserX submits the record for approval, it will go to UserB for approval since Opportunity owner is UserA.

If Use Approver Field of Opportunity Owner is disabled,
1. If UserA submits the record for approval, it will go to UserB since UserA's manager is UserB.
2. If UserX submits the record for approval, it will go to UserY since UserX's manager is UserY.

13. Subquery in SOQL
Sample Query:

SELECT Id, Name,
(SELECT FirstName, LastName, Title, Email, Phone FROM Contacts),
(SELECT Name, StageName, Amount, CloseDate FROM Opportunities),
(SELECT CaseNumber, ContactId, Subject, Priority, Status FROM Cases) FROM Account LIMIT 10


For Custom object, ChildObject__r is the Child Relationship name which can be found in child object's parent field definition.

SOQL statements cannot query aggregate relationships more than 1 level away from the root entity object.

14. Lightning Flow Runtime vs. Classic Flow Runtime
Depending on how a flow is distributed, users see either the Classic runtime or Lightning runtime UI when they run the flow. Like its name suggests, Lightning runtime looks and feels like Lightning Experience.
Flows that run from a Visualforce component always use Classic runtime. Flows that run from a Lightning page, flow action, or custom Aura component always use Lightning runtime. All other methods depend on whether Lightning runtime has been enabled in your org’s Process Automation settings.

https://help.salesforce.com/articleView?id=flow_distribute_runtime.htm&type=5

15. Refresh the Cache for a Wired Property
Sometimes, you know that the cache is stale. If the cache is stale, the component needs fresh data. To query the server for updated data and refresh the cache, import and call the refreshApex(wiredProperty) function.

import { refreshApex } from '@salesforce/apex';
refreshApex(wiredProperty)
wiredProperty—A property or method annotated with @wire. To refresh a wired method, you must pass the argument the wired method receives (which is the wired value).

How to align lightning-button in Salesforce LWC?

Sample Code:

HTML:

<template>
   
    <div class="slds-clearfix">
        <div class="slds-float_left">
            <lightning-button label="Left" class="slds-m-left_x-small"></lightning-button>
        </div>
    </div>
    <div class="slds-clearfix">
        <div class="slds-align_absolute-center">
            <lightning-button label="Center" class="slds-m-left_x-small"></lightning-button>
        </div>
    </div>
    <div class="slds-clearfix">
        <div class="slds-float_right">
            <lightning-button label="Right" class="slds-m-left_x-small"></lightning-button>
        </div>
    </div>
   
</template>


Output:


March 15, 2020

Contract and Service Contract in Salesforce

Service contracts
Service contracts are agreements between you and your customers for a type of customer support.

Service contracts can represent different kinds of customer support, such as warranties, subscriptions, or service level agreements (SLAs).

To set up service contracts, from Setup, click Customize --> Entitlement Management --> Service Contracts.

Contract
The Contract object represents a business agreement.

A contract is a written agreement between parties. Many companies use contracts to define the terms for doing business with other companies

March 12, 2020

lightning-datatable with buttons/row actions using Lightning Web Component LWC in Salesforce

Component HTML:

<template> 
     
    <lightning-card title = "Search Accounts" icon-name = "custom:custom63"> 
 
        <div class = "slds-m-around_medium"> 
 
            <lightning-input type = "search" onchange = {handleKeyChange} class = "slds-m-bottom_small" label = "Search" > 
            </lightning-input> 
 
            <template if:true = {accounts}> 
                 
                <div style="height: 300px;"> 
 
                    <lightning-datatable key-field="Id" 
                                         data={accounts} 
                                         columns={columns} 
                                         hide-checkbox-column="true" 
                                         show-row-number-column="true"
                                         onrowaction={handleRowAction}> 
                    </lightning-datatable> 
 
                </div>                  
     
            </template> 
     
            <template if:true = {error}> 
 
                {error}> 
                 
            </template> 
 
        </div> 
 
    </lightning-card> 
 
</template>



Component JS:

import { LightningElement, track } from 'lwc'; 
import fetchAccounts from '@salesforce/apex/AccountController.fetchAccounts';
import { NavigationMixin } from 'lightning/navigation';

const actions = [
    { label: 'View', name: 'view' },
    { label: 'Edit', name: 'edit' },
];
 
const columns = [   
    { label: 'Name', fieldName: 'Name' }, 
    { label: 'Industry', fieldName: 'Industry' },
    {
        type: 'action',
        typeAttributes: { rowActions: actions },
    }, 
];

export default class LightningDataTableLWC extends NavigationMixin( LightningElement ) {
     
    @track accounts; 
    @track error; 
    @track columns = columns; 
 
    handleKeyChange( event ) { 
         
        const searchKey = event.target.value; 
 
        if ( searchKey ) { 
 
            fetchAccounts( { searchKey } )   
            .then(result => { 
 
                this.accounts = result; 
 
            }) 
            .catch(error => { 
 
                this.error = error; 
 
            }); 
 
        } else 
        this.accounts = undefined; 
 
    }

    handleRowAction( event ) {

        const actionName = event.detail.action.name;
        const row = event.detail.row;
        switch ( actionName ) {
            case 'view':
                this[NavigationMixin.Navigate]({
                    type: 'standard__recordPage',
                    attributes: {
                        recordId: row.Id,
                        actionName: 'view'
                    }
                });
                break;
            case 'edit':
                this[NavigationMixin.Navigate]({
                    type: 'standard__recordPage',
                    attributes: {
                        recordId: row.Id,
                        objectApiName: 'Account',
                        actionName: 'edit'
                    }
                });
                break;
            default:
        }

    }

}



Apex Class:

public with sharing class AccountController { 
 
    @AuraEnabled( cacheable = true ) 
    public static List< Account > fetchAccounts( String searchKey ) { 
     
        String strKey = '%' + searchKey + '%'; 
        return [ SELECT Id, Name, Industry FROM Account WHERE Name LIKE: strKey LIMIT 10 ]; 
         
    } 
     
}

 

Output:




How to get the count of selected row in lightning:datatable in Salesforce?

Sample Code:

Component:

  1. <aura:component implements="force:appHostable" controller="AccountListController">  
  2.       
  3.     <aura:attribute type="Account[]" name="acctList"/>  
  4.     <aura:attribute name="mycolumns" type="List"/>  
  5.     <aura:attribute name="selectedAccts" type="List"/>  
  6.       
  7.     <aura:handler name="init" value="{!this}" action="{!c.init}"/>  
  8.       
  9.     <div class="slds-box slds-theme_default">  
  10.           
  11.         <lightning:datatable data="{! v.acctList }"   
  12.                              columns="{! v.mycolumns }"   
  13.                              keyField="id"  
  14.                              onrowselection="{!c.handleSelect}"/>  
  15.         <br/>  
  16.         <center>  
  17.             <lightning:button onclick="{!c.showSelectedName}" label="Alert Size" variant="brand"/>  
  18.         </center>  
  19.           
  20.     </div>  
  21.       
  22. </aura:component> 

JS Controller:

  1. ({  
  2.       
  3.     init : function( component, event, helper ) {  
  4.           
  5.         component.set('v.mycolumns', [  
  6.             {label: 'Account Name', fieldName: 'linkName', type: 'url',   
  7.             typeAttributes: {label: { fieldName: 'Name' }, target: '_blank'}},  
  8.             {label: 'Industry', fieldName: 'Industry', type: 'text'},  
  9.             {label: 'Type', fieldName: 'Type', type: 'Text'}  
  10.         ]);  
  11.           
  12.         helper.fetchAccounts( component, event );  
  13.           
  14.     },  
  15.       
  16.     handleSelect : function( component, event, helper ) {  
  17.           
  18.         var selectedRows = event.getParam( 'selectedRows' );   
  19.         var setRows = [];  
  20.         for ( var i = 0; i < selectedRows.length; i++ ) {  
  21.               
  22.             setRows.push( selectedRows[ i ] );  
  23.   
  24.         }  
  25.         component.set( "v.selectedAccts", setRows );  
  26.           
  27.     },  
  28.       
  29.     showSelectedName : function( component, event, helper ) {  
  30.           
  31.         var records = component.get( "v.selectedAccts" );  
  32.         alert( records.length );  
  33.           
  34.     }  
  35.   
  36. }) 

JS Helper:

  1. ({  
  2.       
  3.  fetchAccounts : function(component, event) {  
  4.     
  5.         var action = component.get("c.fetchAccts");  
  6.           
  7.         action.setCallback(this, function(response) {  
  8.               
  9.             var state = response.getState();  
  10.               
  11.             if (state === "SUCCESS") {  
  12.                   
  13.                 var records = response.getReturnValue();  
  14.                 records.forEach(function(record) {  
  15.                       
  16.                     record.linkName = '/' + record.Id;  
  17.                     record.CheckBool = false;  
  18.                       
  19.                 });     
  20.                   
  21.                 component.set("v.acctList", records);  
  22.                   
  23.             }              
  24.               
  25.         });  
  26.           
  27.         $A.enqueueAction(action);  
  28.           
  29.  }  
  30.       
  31. }) 

Apex Class:

  1. public class AccountListController {  
  2.       
  3.     @AuraEnabled  
  4.     public static List < Account > fetchAccts() {  
  5.           
  6.         return [ SELECT Id, Name, Industry, Type FROM Account LIMIT 5 ];  
  7.           
  8.     }  
  9.       

Output: