Showing posts with label Lightning. Show all posts
Showing posts with label Lightning. Show all posts

Tuesday, December 15, 2020

Inline Editing in lightning-datatable in Salesforce Lightning Web Component(lwc)

 This post explains, inline editing in lightning-datatable in salesforce lightning web components(lwc).


HTML Code:

<template>
    <lightning-card title="Inline Edit With Lightning Datatable in LWC">
        <template if:true={contacts.data}>
            <lightning-datatable key-field="Id" 
                                 data={contacts.data} 
                                 columns={columns} 
                                 onsave={handleSave}
                                 draft-values={saveDraftValues} 
                                 hide-checkbox-column 
                                 show-row-number-column>
            </lightning-datatable>
        </template>
    </lightning-card>
</template>


Javascript Code:

import { LightningElement, wire, track } from 'lwc';
import getContacts from '@salesforce/apex/LWCExampleController.getContacts';
import { updateRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';
// datatable columns
const columns = [
    {
        label: 'Name',
        fieldName: 'Name',
        type: 'text',
    }, {
        label: 'FirstName',
        fieldName: 'FirstName',
        type: 'text',
        editable: true,
    }, {
        label: 'LastName',
        fieldName: 'LastName',
        type: 'text',
        editable: true,
    }, {
        label: 'Phone',
        fieldName: 'Phone',
        type: 'phone',
        editable: true
    }
];

export default class InlineEditTable extends LightningElement {

    columns = columns;
    @track contacts;
    saveDraftValues = [];

    @wire(getContacts)
    cons(result) {
        this.contacts = result;
        if (result.error) {
            this.contacts = undefined;
        }
    };

    handleSave(event) {
        this.saveDraftValues = event.detail.draftValues;
        const recordInputs = this.saveDraftValues.slice().map(draft => {
            const fields = Object.assign({}, draft);
            return { fields };
        });

        // Updateing the records using the UiRecordAPi
        const promises = recordInputs.map(recordInput => updateRecord(recordInput));
        Promise.all(promises).then(res => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Records Updated Successfully!!',
                    variant: 'success'
                })
            );
            this.saveDraftValues = [];
            return this.refresh();
        }).catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error',
                    message: 'An Error Occured!!',
                    variant: 'error'
                })
            );
        }).finally(() => {
            this.saveDraftValues = [];
        });
    }

    // This function is used to refresh the table once data updated
    async refresh() {
        await refreshApex(this.contacts);
    }
}

Apex Code:

public inherited sharing class LWCExampleController {

    @AuraEnabled(Cacheable = true)
    public static List<Contact> getContacts() {
        return [SELECT Id, Name, FirstName, LastName, Phone, Email 
                FROM Contact 
                WHERE Email != null 
                AND Phone != null 
                ORDER BY CreatedDate DESC NULLS LAST limit 10];
    }
}


Output:



Monday, March 30, 2020

Tree Grid in Lightning Web Components(lwc)

HTML Code
<template>
    <lightning-card title="Tree Grid in Lightning Web Components">
        <lightning-tree-grid columns={gridColumns} data={gridData} key-field="Id">
        </lightning-tree-grid>
    </lightning-card>
</template>

Javascript Code
import {
    LightningElement,
    wire
} from 'lwc';
import fetchAccs from '@salesforce/apex/GenericController.returnAccsWithCons';

export default class TreeGridInLWC extends LightningElement {
    gridData;

    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'

        }
    ];


    @wire(fetchAccs)
    accsWithCons({
        error,
        data
    }) {
        if (data) {
            let parseData = JSON.parse(JSON.stringify(data));

            for (let i = 0; i < parseData.length; i++) {
                parseData[i]._children = parseData[i]['Contacts'];
                delete parseData[i]['Contacts'];
            }

            this.gridData = parseData;
        } else if (error) {
            console.log('error ====> ' + JSON.stringify(error));
        }
    }
}
Apex Class
public inherited sharing class GenericController {
    
    @AuraEnabled(Cacheable=true)
    public static list<Account> returnAccsWithCons(){
        return [SELECT Id, Name, Industry, Type, (SELECT Id, FirstName, LastName FROM Contacts) FROM Account];
    }
}

Output

Wednesday, March 25, 2020

Progress ring/circular in lightning web components(lwc)

HTML Code
<template>
    <lightning-card title="Progress ring in Lightning Web Component"><br/>
        <div>
            <lightning-progress-ring variant="base-autocomplete" value={progress} size="large" class="slds-align_absolute-center"> </lightning-progress-ring>
        </div>
        <div class="slds-text-align--center slds-text-title" style="color:forestgreen;">
            {processStatus}
        </div>
    </lightning-card>
</template>

JS Code
import { LightningElement, track } from 'lwc';

export default class ProgressBarDemoInLWC extends LightningElement {
    progress = 0;
    processStatus = 'In Progress';
    connectedCallback() {
        // eslint-disable-next-line @lwc/lwc/no-async-operation
        this._interval = setInterval(() => {
            this.progress = this.progress + 5;
            this.processStatus = 'Processing => ' + this.progress +'/100';
            if(this.progress === 100) {
                clearInterval(this._interval);
                this.processStatus = 'Completed';
            }
        }, 300);

    }
}

Output

Sunday, March 22, 2020

How to Open files in separate tab/new tab in visual studio code

By default, in Visual Studio Code, files open in the same tab instead of a separate tab.

To force to open separate tab/new tab in visual studio code then Disable the Preview Mode.

File -> Preferences -> Settings

In Settings -> Type “preview” in the search text field and uncheck the Enable Preview as highlighted.

That's it, now when you open any file in visual studio code it opens the file in a separate window/tab.

How to set default value in Combo box in Lightning Web Components(lwc)

To set the default value in the Combo box assign the value in js code directly.

Ex:

HTML Code
<template>
    <lightning-combobox
            name="progress"
            label="Status"
            value={value}
            placeholder="Select Progress"
            options={options}
            onchange={handleChange} ></lightning-combobox>

    <p>Selected value is: {value}</p>
</template>

JS Code
import { LightningElement, track } from 'lwc';

export default class ComboboxBasic extends LightningElement {
    value = 'inProgress';

    get options() {
        return [
            { label: 'New', value: 'new' },
            { label: 'In Progress', value: 'inProgress' },
            { label: 'Finished', value: 'finished' },
        ];
    }

    handleChange(event) {
        this.value = event.detail.value;
    }
}

Output

Wednesday, March 4, 2020

How to create custom URL button or link in Lightning experience with default field values in salesforce

From Spring'20 onwards you can create the custom URL button with default field values.

you can define the default values while launches the custom button or custom link or custom code to create a new record with prepopulated field values.

Sample Code
/lightning/o/Account/new?defaultFieldValues=
    Name={!URLENCODE(Account.Name)},
    OwnerId={!Account.OwnerId},
    AccountNumber={!Account.AccountNumber},
    NumberOfEmployees=35000,
    CustomCheckbox__c={!IF(Account.SomeCheckbox__c, true, false)}

Note: The URLENCODE function works only when creating custom buttons and links. You can’t use it for custom fields.

Demo
Create a new opportunity from the account detail page with populate account values and some of the prepopulated filled values in new opportunity creation form.

Step:1



Step: 2
add the button to the account page layout and click on the new opportunity button.



Output


Note:
  •  The URLENCODE function works only when creating custom buttons and links. You can’t use it for custom fields.
  • URL Hack working only in New Record and not in the Edit forms

Demo Sample:
/lightning/o/Opportunity/new?defaultFieldValues=
    Name={!URLENCODE(Account.Name)},
    OwnerId={!Account.OwnerId},
    Days_To_Close__c=30,
    TotalOpportunityQuantity=2,
    NextStep=Call%20to%20customer,
    Type=New%20Customer



Refereence
https://releasenotes.docs.salesforce.com/en-us/spring20/release-notes/rn_general_lex_navigate_to_record_dfv.htm

Friday, November 8, 2019

How to get available Lightning Components In your org

Note: My domain should be enabled in your org

  • Login to your org 
  • Add componentReference/suite.app in your org domain URL
Ex:
https://<yourorgdomain>.lightning.force.com/componentReference/suite.app

you can see all the available components of your Org along with Salesforce Lightning Component and Lightning web components examples.


Saturday, October 19, 2019

How to test salesforce performance and speed in Lightning Experience

If your Users are experiencing slow page-loading times when using Lightning Experience, it may be related to one or more of the following issue types.
  • Geographical
  • Device
  • Browser
  • Salesforce organization configuration issues

It is a simple online tool to measure your browser Javascript speed and your internet connection speed to Salesforce’s servers. 

How to access the tool?

To access this tool simply log-on to your Salesforce org and remove everything after “[your domain name].lightning.force.com/” in the browser URL and add the speedtest.jsp 
Ex:
https://<your domain>.lightning.force.com/speedtest.jsp
OR
https://[instance].salesforce.com/speedtest.jsp


Click the "Test Speed" button, tool tests all the performances, Once the test is finished, results will be displayed.

Reference
https://help.salesforce.com/articleView?id=000316034&language=en_US&type=1&mode=1

Sunday, September 22, 2019

Display Radio Buttons Group In Horizontal View in Lightning Component(AURA)

This post explains how to implement a radio group in the horizontal view in lightning components.


Component

<aura:component controller="LWCExampleController" implements="flexipage:availableForAllPageTypes">
    <!--Declaring variables-->
    <aura:attribute name="picklistValues" type="String[]"/>
    <aura:attribute name="selectedValue" type="String"/>
    <aura:attribute name="mapPicklistValues" type="Map" />

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

    <div class="slds-box slds-theme_default">
        <h2>
            <p>Radio Buttons in Horizontal View in Lightning Component</p>
        </h2><br/>
        <aura:iteration items="{!v.picklistValues}" var="item">
            <fieldset style="display: block; float: left;">
                <div class="slds-form-element__control">
                    <span class="slds-radio">
                        <input id="{!item}" name="radiogroup" onchange="{!c.handleSelected}" type="radio" value="{!item}"/>
                        <label class="slds-radio__label" for="{!item}">
                            <span class="slds-radio_faux"></span>
                            <span class="slds-form-element__label">{!item}</span>
                        </label>
                    </span>
                </div>
            </fieldset>
        </aura:iteration><br/><br/>
        <aura:if isTrue="{!not(empty(v.selectedValue))}">
            <div>
                Selected Vlaue:
                <b>{!v.selectedValue}</b>
            </div>
        </aura:if>
    </div>
</aura:component>

Component Controller:
({
    fetchPicklistValues : function(component, event, helper) {
       
        var action = component.get("c.getAccRatings");
        var options=[];
        action.setCallback(this, function(response) {
            let state = response.getState();
            if(state === 'SUCCESS') {
                var mapValues = response.getReturnValue();
                component.set('v.mapPicklistValues', mapValues);
                let picklistValuesList = [];

                for(let key in mapValues) { 
                    picklistValuesList.push(mapValues[key]);
                }
            
                component.set("v.picklistValues", picklistValuesList);
            }
             
        });
        $A.enqueueAction(action); 
    },

    handleSelected : function(component, event, helper) {
        let currentValue = event.target.value;
        
        let mapValues = component.get('v.mapPicklistValues');
        let selectedValue;
        for(let key in mapValues) {
            if(currentValue == mapValues[key]) {
                selectedValue = key;
                break;
            }
        }
        component.set('v.selectedValue', selectedValue);

    }
})

Apex Class

public inherited sharing class LWCExampleController {
    @AuraEnabled
    public static map<String, String> getAccRatings(){
        map<String, String> options = new map<String, String>();
        Schema.DescribeFieldResult fieldResult = Account.Rating.getDescribe();
        List<Schema.PicklistEntry> lstPicklistValues = fieldResult.getPicklistValues();
        for (Schema.PicklistEntry iterator: lstPicklistValues) {
            options.put(iterator.getValue(), iterator.getLabel());
        }
        return options;
    }
}

Output


Monday, September 16, 2019

Disable Browser Cache During Lightning Componet(AURA), Lightning Web Component Development(lwc)

Path:
From Setup, enter Session Settings in the Quick Find box, and then select Session Settings.
Deselect the checkbox for “Enable secure and persistent browser caching to improve performance”.
then click save.


Note:
Disabling secure and persistent browser caching has a significant negative performance impact on Lightning Experience. Always enable the setting in production orgs.

Display Radio Buttons Group in Horizontal view in Lightning Web Component(lwc)

This post explains how to display radio buttons group in Horizontal view in Lightning Web Components(lwc)


radioGroupInHorizontal.html
<template>
    <lightning-card title="Radio Buttons Group Horizontal View in Lightning Web Component"><br/>
        <div style="margin-left:3%;">
            <template for:each={options} for:item="item">
                <fieldset key={item.value} style="display: block; float: left;">
                    <div class="slds-form-element__control">
                        <span class="slds-radio">
                            <input name="radiogroup" id={item.value} type="radio" value={item.value} onchange={handleSelected}/>
                            <label class="slds-radio__label" for={item.value}>
                                <span class="slds-radio_faux"></span>
                                <span class="slds-form-element__label">{item.label}</span>
                            </label>
                        </span>
                    </div>
                </fieldset>
            </template><br/><br/>

            <div if:true={selectedValue}>
                Selected Vlaue: <b>{selectedValue}</b>
            </div>
        </div>

    </lightning-card>
</template>

radioGroupInHorizontal.js
import { LightningElement, wire, track} from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import Rating_FIELD from '@salesforce/schema/Account.Rating';

export default class RadioGroupInHorizontal extends LightningElement {
    @track selectedValue;
    @track options = [];

    // object info using wire service
    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    objectInfo;

    // Getting Account Rating Picklist values using wire service
    @wire(getPicklistValues, { recordTypeId: '$objectInfo.data.defaultRecordTypeId', fieldApiName: Rating_FIELD})
    ratingPicklistValues({error, data}) {
        if(data) {
            window.console.log('result ===> '+JSON.stringify(data.values));
            this.options = data.values;
        }
        else if(error) {
            window.console.log('error ===> '+JSON.stringify(error));
        }
    }

    // handle the selected value
    handleSelected(event) {
       window.console.log('selected value ===> '+event.target.value);
       this.selectedValue = event.target.value;
    }

}

RadioGroupInHorizontal.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="RadioGroupInHorizontal">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Output


Tuesday, July 30, 2019

How to Unescape HTML in Lightning Component

Use  <aura:unescapedHtml /> component to unescape the HTML in Lightning Component.


Example

Lightning Component
<aura:component implements="flexipage:availableForAllPageTypes">
    <aura:attribute name="strURL" type="String" />
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    <lightning:card>
        <p class="slds-m-around--xx-large">
            <h2>Welcome to my <aura:unescapedHtml value="{!v.strURL}"/></h2>
        </p>
    </lightning:card>
</aura:component>
JS Controller
({
     doInit : function(component, event, helper) {
        let strURL = '<a href="https://www.salesforcecodecrack.com/" target="_blank">Salesforce Code Crack</a> Blog.';
        component.set('v.strURL', strURL); 
     }
})
Resource
aura:unescapedHtml

Friday, June 28, 2019

How to Delete multiple selected records in Lightning Datatable in lightning web components(lwc)

This post explains how to delete multiple selected records in lightning datatable in lightning web components(lwc)



Example
deleteRowsInDatatableLWC.html
<template>
     <lightning-card title="Delete Selected Rows in Datatable" icon-name="standard:contact" > <br/>
        <div style="width: auto;">
            <template if:true={data}>
                    <div class="slds-grid slds-gutters">
                            <div class="slds-col">
                              <span><p style="margin-left: 5%">Selected Records: <b style="color:red;">{recordsCount}</b></p></span>
                            </div>
                            <div class="slds-col">
                                <span>                    
                                    <lightning-button label={buttonLabel}
                                                      icon-name="utility:delete"
                                                      disabled={isTrue}
                                                      variant="destructive" 
                                                      onclick={deleteAccounts}
                                                      style="margin-left: 40%"></lightning-button>
                                </span>
                            </div>
                        </div><br/>

                    <lightning-datatable data={data}
                                     columns={columns}
                                     key-field="id"
                                     onrowselection={getSelectedRecords}></lightning-datatable>
            </template>

        </div>
    </lightning-card>   
</template>
deleteRowsInDatatableLWC.js
import {LightningElement, track, wire} from 'lwc';

// importing apex class methods
import getContacts from '@salesforce/apex/LWCExampleController.getContacts';
import delSelectedCons from '@salesforce/apex/LWCExampleController.deleteContacts';

// importing to show toast notifictions
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

// importing to refresh the apex after delete the records.
import {refreshApex} from '@salesforce/apex';

// datatable columns
const columns = [
    {
        label: 'FirstName',
        fieldName: 'FirstName'
    }, {
        label: 'LastName',
        fieldName: 'LastName'
    }, {
        label: 'Phone',
        fieldName: 'Phone',
        type: 'phone'
    }, {
        label: 'Email',
        fieldName: 'Email',
        type: 'email'
    }
];

export default class DeleteRowsInDatatableLWC extends LightningElement {
    // reactive variable
    @track data;
    @track columns = columns;
    @track buttonLabel = 'Delete Selected Contacts';
    @track isTrue = false;
    @track recordsCount = 0;

    // non-reactive variables
    selectedRecords = [];
    refreshTable;
    error;

    // retrieving the data using wire service
    @wire(getContacts)
    contacts(result) {
        this.refreshTable = result;
        if (result.data) {
            this.data = result.data;
            this.error = undefined;

        } else if (result.error) {
            this.error = result.error;
            this.data = undefined;
        }
    }


    // Getting selected rows 
    getSelectedRecords(event) {
        // getting selected rows
        const selectedRows = event.detail.selectedRows;
        
        this.recordsCount = event.detail.selectedRows.length;

        // this set elements the duplicates if any
        let conIds = new Set();

        // getting selected record id
        for (let i = 0; i < selectedRows.length; i++) {
            conIds.add(selectedRows[i].Id);
        }

        // coverting to array
        this.selectedRecords = Array.from(conIds);

        window.console.log('selectedRecords ====> ' +this.selectedRecords);
    }


    // delete records process function
    deleteAccounts() {
        if (this.selectedRecords) {
            // setting values to reactive variables
            this.buttonLabel = 'Processing....';
            this.isTrue = true;

            // calling apex class to delete selected records.
            this.deleteCons();
        }
    }


    deleteCons() {
        delSelectedCons({lstConIds: this.selectedRecords})
        .then(result => {
            window.console.log('result ====> ' + result);

            this.buttonLabel = 'Delete Selected Contacts';
            this.isTrue = false;

            // showing success message
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success!!', 
                    message: this.recordsCount + ' Contacts are deleted.', 
                    variant: 'success'
                }),
            );
            
            // Clearing selected row indexs 
            this.template.querySelector('lightning-datatable').selectedRows = [];

            this.recordsCount = 0;

            // refreshing table data using refresh apex
            return refreshApex(this.refreshTable);

        })
        .catch(error => {
            window.console.log(error);
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error while getting Contacts', 
                    message: error.message, 
                    variant: 'error'
                }),
            );
        });
    }  

}
deleteRowsInDatatableLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="DeleteRowsInDatatableLWC">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Apex Class
public inherited sharing class LWCExampleController {

    @AuraEnabled(Cacheable = true)
    public static List<Contact> getContacts(){
        return [SELECT Id, FirstName,LastName, Phone, Email FROM Contact ORDER BY Name limit 10];
    }
    
    @AuraEnabled
    public static void deleteContacts(list<Id> lstConIds){
        try {
            list<Contact> lstConsToDelete = new list<Contact>();
            System.debug('lstConIds ====> '+lstConIds);
            for(Id idCon : lstConIds) {
                lstConsToDelete.add(new Contact(Id = idCon));
            }
            if(!lstConsToDelete.isEmpty()) {
                delete lstConsToDelete;
            }
        }
        catch(Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }
    }
}
Output


Thursday, February 14, 2019

How to disable Lightning button after click the button

This post explains how to disable the lightning button in Lightning component.

Demo:

DisableButtonComponent
<aura:component controller="LightningRelatedExamples" implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <aura:attribute name="objAcc" type="Account"  default="{'sobjectType':'Account', 
                                                           'Name': '',
                                                           'Phone': '',
                                                           'Industry': '', 
                                                           'Type': ''}"/>
    <aura:attribute name="isHide" type="Boolean" default="false" />
    
    <!-- Notification library to show notifications-->
    <lightning:notificationsLibrary aura:id="notifLib"/>
    <div class="slds-theme_default">
        <div class="slds-form-element">
            <center>
                <label class="slds-form-element__label slds-text-heading_medium slds-m-bottom_medium" for="form-element-01">Create Account Form</label>
            </center>
            <div class="slds-form-element__control">
                <lightning:input name="name" type="text" required="true" label="Account Name" value="{!v.objAcc.Name}" />
                <lightning:input name="phone" type="text" label="Phone" value="{!v.objAcc.Phone}" />
                <lightning:input name="industry" type="text" label="Industry" value="{!v.objAcc.Industry}" />
                <lightning:input name="type" type="text" label="Account Type" value="{!v.objAcc.Type}" /> <br/>
                <center>
                    <lightning:button variant="brand" disabled="{!v.isHide}" label="{!v.isHide == true ? 'Account Created' : 'Create Account'}" onclick="{!c.saveAccount}" /> 
                </center>
            </div>
        </div>
    </div>
</aura:component>

DisableButtonComponentController.js
({
    saveAccount : function(component, event, helper) {
        var objAccount = component.get("v.objAcc");
        var action = component.get('c.insertAccount');
        action.setParams({
            objAcc:objAccount
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === "SUCCESS") {
                component.find('notifLib').showToast({
                    "variant": "success",
                    "title": objAccount.Name,
                    "message": "The record has created successfully."
                });
                component.set('v.isHide', true);  
            }
        });
        $A.enqueueAction(action);
    }
})

Apex Controller
public inherited Sharing class LightningRelatedExamples {
    
    @AuraEnabled
    public static void insertAccount(Account objAcc) {
        if(objAcc != null) {
            try {
                insert objAcc;
            }
            catch(Exception ex) {
                 throw new AuraHandledException(ex.getMessage());
            }
        }
    }
}

Result