Wednesday, July 31, 2019

Difference between var, let, const in Javascript

From ES6 we have three ways to declare a variables
var a = 48;
const b = 'Hello Shaik';
let c = true;
The type of declaration depends on the scope. The scope is the fundamental concept in all programming languages that defines the visibility of a variable.

Var

 The var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.

Ex:
function testVar() {
  var x = 1;
  if (true) {
    var x = 2;  // same variable
    console.log(x);  // 2
  }
  console.log(x);  // 2
}
Output

let

let allows you to declare variables that are limited in scope to the block, statement, or expression in which they are used. 
if you run the below the code it will throw an error

if (true) {
let name = 'Hi Shaik';
}
alert(name); //generates an error

In this above case, the name variable is accessible only in the scope of the if statement because it was declared as let.
Ex:
function letTest() {
  let x = 1;
  if (true) {
    let x = 2;  // different variable
    console.log(x);  // 2
  }
  console.log(x);  // 1
}
Output


const

const variables have the same scope as variables declared using let. The difference is that const variables are immutable - they are not allowed to be reassigned.

Ex:
const a = 'Hello Shaik';
a = 'Bye';
console.log(a);
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

Saturday, July 27, 2019

How to check Forecast is enabled or not for User using SOQL

This simple query checks the forecast is enabled or not user
SELECT Id, ForecastEnabled FROM User where Id = '005B0000005lewT'
Result

Resource
https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_objects_user.htm

How to query Salesforce Logged in Users information Using SOQL

This simple SOQL query returns the User Information and logged information in salesforce.
It returns the type of sessions user have a logged-in system.

SOQL Query
Select Id, UsersId, Users.Name, UserType, SourceIp, SessionType, SessionSecurityLevel, ParentId, LoginType, LastModifiedDate, CreatedDate From AuthSession
Result

Resource
AuthSession SOAP API

Wednesday, July 10, 2019

How to increase Modal/Popup width in Lightning Web Component(lwc)

This post explains how to increase the modal/popup width in lightning web component(lwc)


IncreaseWidthOfModalBoxInLWC.html
<template>

    <center class="slds-theme_default">
        <p>
            <b>Show Modal Box using Lightning Web Componentes</b>
        </p><br/><br/>
        <lightning-button label="Show Modal" onclick={openmodal} variant="brand"></lightning-button>
    </center><div></div>

    <template if:true={openmodel}>
        <section aria-describedby="modal-content-id-1" aria-labelledby="modal-heading-01" aria-modal="true" class="slds-modal slds-fade-in-open" role="dialog" tabindex="-1">
            <div class="slds-modal__container">
                <header class="slds-modal__header">
                    <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" onclick={closeModal} title="Close">
                        <lightning-icon icon-name="utility:close" size="medium" variant="inverse"></lightning-icon>
                        <span class="slds-assistive-text">Close</span>
                    </button>
                    <h2 class="slds-text-heading_medium slds-hyphenate" id="modal-heading-01">Modal Box Example</h2>
                </header>
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
                    <center>
                        <h2>
                            <b>Welcome to Salesforce Code Crack</b>
                        </h2><br/>
                        <p>Happy Learning!!!</p>
                    </center>
                </div>
                <footer class="slds-modal__footer">
                    <lightning-button label="Cancel" onclick={closeModal} variant="neutral"></lightning-button>&nbsp;&nbsp;&nbsp;&nbsp;
                    <lightning-button label="Save" onclick={saveMethod} variant="brand"></lightning-button>
                </footer>
            </div>
        </section>
        <div class="slds-backdrop slds-backdrop_open"></div>
    </template>
</template>

Approach 1:

Using external CSS File
To create a .css file,
follow the step:
1. Right-click on your lwc component.
2. Select New File
3. Name the file same as your lwc component with the .css extension


IncreaseWidthOfModalBoxInLWC.css
.slds-modal__container {
    max-width: 80rem !important;
    width: 80% !important;
}

Approach 2:

Using Static Resource

Create the normal .css file, upload css file in static resources and import static resource file in your Lightning web component
check below link how to import static resources in lwc


IncreaseWidthOfModalBoxInLWC.js
import { LightningElement, track } from 'lwc';

export default class IncreaseWidthOfModalBoxInLWC extends LightningElement {
    @track openmodel = false;
    openmodal() {
        this.openmodel = true
    }
    closeModal() {
        this.openmodel = false
    } 
    saveMethod() {
        alert('save method invoked');
        this.closeModal();
    }
}

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

Friday, July 5, 2019

Lightning Data table with sorting in Lightning Web Component(lwc)

This post explains how to sort the lightning data table data in lightning web components(lwc)



Example:
HTML Code
<template>
    <lightning-card title="Sorting Data in Lightning Datatable in LWC" icon-name="standard:contact" > <br/>
        <div style="width: auto;">
            <template if:true={data}>
                <lightning-datatable data={data}
                                     columns={columns}
                                     key-field="id"
                                     sorted-by={sortBy}
                                     sorted-direction={sortDirection}
                                     onsort={handleSortdata}
                                     hide-checkbox-column="true"></lightning-datatable>
            </template>

        </div>
    </lightning-card>
</template>
Javascript Controller Code
import {LightningElement, wire, track} from 'lwc';

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

// datatable columns with row actions
const columns = [
    {
        label: 'FirstName',
        fieldName: 'FirstName',
        sortable: "true"
    }, {
        label: 'LastName',
        fieldName: 'LastName',
        sortable: "true"
    }, {
        label: 'Phone',
        fieldName: 'Phone',
        type: 'phone',
        sortable: "true"
    }, {
        label: 'Email',
        fieldName: 'Email',
        type: 'email'
    },
];

export default class DataTableWithSortingInLWC extends LightningElement { 
    // reactive variable
    @track data;
    @track columns = columns;
    @track sortBy;
    @track sortDirection;

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

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

    handleSortdata(event) {
        // field name
        this.sortBy = event.detail.fieldName;

        // sort direction
        this.sortDirection = event.detail.sortDirection;

        // calling sortdata function to sort the data based on direction and selected field
        this.sortData(event.detail.fieldName, event.detail.sortDirection);
    }

    sortData(fieldname, direction) {
        // serialize the data before calling sort function
        let parseData = JSON.parse(JSON.stringify(this.data));

        // Return the value stored in the field
        let keyValue = (a) => {
            return a[fieldname];
        };

        // cheking reverse direction 
        let isReverse = direction === 'asc' ? 1: -1;

        // sorting data 
        parseData.sort((x, y) => {
            x = keyValue(x) ? keyValue(x) : ''; // handling null values
            y = keyValue(y) ? keyValue(y) : '';

            // sorting values based on direction
            return isReverse * ((x > y) - (y > x));
        });

        // set the sorted data to data table data
        this.data = parseData;

    }

}
Configuration XML File

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="dataTableWithSortingInLWC">
    <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 limit 15];
    }
}
Result

Thursday, July 4, 2019

Lightning DataTable With Row Actions in Lightning Web Component(lwc)

This post explains how to handle row actions in the lightning data table in lightning web components(lwc)



Example:
HTML Code
<template>
     <lightning-card title="Datatable with Row Actions" icon-name="standard:contact" > <br/>
        <div style="width: auto;">
            <template if:true={data}>

                <lightning-datatable data={data}
                                     columns={columns}
                                     key-field="id"
                                     hide-checkbox-column="true"
                                     onrowaction={handleRowActions}></lightning-datatable>
            </template>

        </div>

        <!-- Spinner -->
        <div if:true={showLoadingSpinner}>
            <lightning-spinner alternative-text="Loading" size="large"></lightning-spinner>
        </div>

        <!-- Detail view modal -->
        <template if:true={bShowModal}>
            <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">
                <!-- modal header -->
                <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" alternative-text="close" variant="inverse" size="small" ></lightning-icon>
                    </button>
                    
                    <h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate" if:false={isEditForm}>Record Detail</h2>
                    <h2 id="modal-heading-02" class="slds-text-heading_medium slds-hyphenate" if:true={isEditForm}>Update Record Values</h2>
                </header>
                <!-- modal body -->
                <div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1" if:false={isEditForm}>
                    <dl class="slds-list_horizontal slds-wrap">
                        <dt class="slds-item_label slds-truncate" title="First Name">First Name:</dt>
                        <dd class="slds-item_detail slds-truncate">{record.FirstName}</dd>
                        <dt class="slds-item_label slds-truncate" title="LastName">Last Name:</dt>
                        <dd class="slds-item_detail slds-truncate">{record.LastName}</dd>
                        <dt class="slds-item_label slds-truncate" title="Phone">Phone :</dt>
                        <dd class="slds-item_detail slds-truncate"><lightning-formatted-phone value={record.Phone} ></lightning-formatted-phone></dd>
                        <dt class="slds-item_label slds-truncate" title="Email">Email :</dt>
                        <dd class="slds-item_detail slds-truncate"><lightning-formatted-email value={record.Email} ></lightning-formatted-email></dd>
                    </dl>
                </div>
                
                <!-- showing record edit form -->
                <div if:true={isEditForm} class="slds-theme_default">
                    <lightning-record-edit-form layout-type="Full" record-id={currentRecordId} object-api-name="Contact" onsubmit={handleSubmit} onsuccess={handleSuccess}>
                        <lightning-messages></lightning-messages>
                        <lightning-output-field field-name="AccountId"></lightning-output-field>
                        <lightning-input-field field-name="FirstName"></lightning-input-field>
                        <lightning-input-field field-name="LastName"></lightning-input-field>
                        <lightning-input-field field-name="Email"></lightning-input-field>
                        <lightning-input-field field-name="Phone"></lightning-input-field><br/>
                        
                        <div style="text-align:center;">
                            <lightning-button class="slds-m-top_small"
                                              variant="brand"
                                              type="submit"
                                              name="update"
                                              label="Update Record"></lightning-button>
                        </div>
                    </lightning-record-edit-form><br/>
                    <div></div>
                </div>

                <!-- modal footer start-->
                <footer class="slds-modal__footer" if:false={isEditForm}>
                    <lightning-button variant="brand"
                                      label="Close"
                                      title="Close"
                                      onclick={closeModal}></lightning-button>
                </footer>
            </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
           
        </template>
    </lightning-card>   
</template>
Javascript controller code
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 if any record changes the datas
import {refreshApex} from '@salesforce/apex';

// row actions
const actions = [
    { label: 'Record Details', name: 'record_details'}, 
    { label: 'Edit', name: 'edit'}, 
    { label: 'Delete', name: 'delete'}
];

// datatable columns with row actions
const columns = [
    { label: 'FirstName', fieldName: 'FirstName' }, 
    { label: 'LastName', fieldName: 'LastName' },
    { label: 'Phone', fieldName: 'Phone', type: 'phone'}, 
    { label: 'Email', fieldName: 'Email', type: 'email' }, 
    {
        type: 'action',
        typeAttributes: {
            rowActions: actions,
            menuAlignment: 'right'
        }
    }
];

export default class DeleteRowsInDatatableLWC extends LightningElement { 
    // reactive variable
    @track data;
    @track columns = columns;
    @track record = [];
    @track bShowModal = false;
    @track currentRecordId;
    @track isEditForm = false;
    @track showLoadingSpinner = false;

    // 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;
        }
    }

    handleRowActions(event) {
        let actionName = event.detail.action.name;

        window.console.log('actionName ====> ' + actionName);

        let row = event.detail.row;

        window.console.log('row ====> ' + row);
        // eslint-disable-next-line default-case
        switch (actionName) {
            case 'record_details':
                this.viewCurrentRecord(row);
                break;
            case 'edit':
                this.editCurrentRecord(row);
                break;
            case 'delete':
                this.deleteCons(row);
                break;
        }
    }

    // view the current record details
    viewCurrentRecord(currentRow) {
        this.bShowModal = true;
        this.isEditForm = false;
        this.record = currentRow;
    }

    // closing modal box
    closeModal() {
        this.bShowModal = false;
    }


    editCurrentRecord(currentRow) {
        // open modal box
        this.bShowModal = true;
        this.isEditForm = true;

        // assign record id to the record edit form
        this.currentRecordId = currentRow.Id;
    }

    // handleing record edit form submit
    handleSubmit(event) {
        // prevending default type sumbit of record edit form
        event.preventDefault();

        // querying the record edit form and submiting fields to form
        this.template.querySelector('lightning-record-edit-form').submit(event.detail.fields);

        // closing modal
        this.bShowModal = false;

        // showing success message
        this.dispatchEvent(new ShowToastEvent({
            title: 'Success!!',
            message: event.detail.fields.FirstName + ' '+ event.detail.fields.LastName +' Contact updated Successfully!!.',
            variant: 'success'
        }),);

    }

    // refreshing the datatable after record edit form success
    handleSuccess() {
        return refreshApex(this.refreshTable);
    }

    deleteCons(currentRow) {
        let currentRecord = [];
        currentRecord.push(currentRow.Id);
        this.showLoadingSpinner = true;

        // calling apex class method to delete the selected contact
        delSelectedCons({lstConIds: currentRecord})
        .then(result => {
            window.console.log('result ====> ' + result);
            this.showLoadingSpinner = false;

            // showing success message
            this.dispatchEvent(new ShowToastEvent({
                title: 'Success!!',
                message: currentRow.FirstName + ' '+ currentRow.LastName +' Contact deleted.',
                variant: 'success'
            }),);

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

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

}

Configuration XML File
<?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());
        }
    }
}
Result:

Resources:
lightning-datatable
record-edit-form

Wednesday, July 3, 2019

How to deploy quick actions using ANT tool

Global Actions
<types> 
<members>New_Case</members> 
<members>New_Opportunity</members>  
<name>QuickAction</name> 
</types> 
Quick actions are related to sObject use below sample
<!-- <members>ObjectName.quickactionname</members> -->
 
<types> 
<members>Account.New_Case</members> 
<members>Lead.New_Opportunity</members>  
<name>QuickAction</name> 
</types>