Saturday, January 26, 2019

Notify Unsaved Changes to User in Lightning Component

This post explains how to use the lightning:unsavedChanges component in lightning.

This component provides a way to notify the UI containment hierarchy of unsaved changes and to participate in saving or discarding those changes based on the user's decision.

Example:

UnsavedChangesComponentDemo
<aura:component implements="flexipage:availableForRecordHome" access="global">
    <lightning:unsavedChanges aura:id="unsaved"
                              onsave="{!c.handleSave}"
                              ondiscard="{!c.handleDiscard}" />
    
    <!-- Notification library to show notifications-->
    <lightning:notificationsLibrary aura:id="notifLib"/>

    <div class="slds-theme_default">
        <center>
            <p style="font-size:medium;font-family:sans-serif;padding:10px;margin:5px">Create New Account</p>
        </center>
        <lightning:recordEditForm aura:id="form"
                                onsuccess="{!c.handleSuccess}"
                                onsubmit="{!c.handleSubmit}"
                                objectApiName="Account">
            <!-- the messages component is for error messages -->
            <lightning:messages />
                    
            <lightning:inputField fieldName="Name" onchange="{!c.handleDataChange}"/>
            <lightning:inputField fieldName="Industry" onchange="{!c.handleDataChange}" />
            <lightning:inputField fieldName="Type" onchange="{!c.handleDataChange}" />
            <lightning:inputField fieldName="Phone" onchange="{!c.handleDataChange}" />
            <lightning:inputField fieldName="Emil" onchange="{!c.handleDataChange}"/>
            <center>
                <div class="slds-m-top_medium">
                    <lightning:button variant="brand" type="submit" name="save" label="Save New Account" />
                </div>
            </center>
        </lightning:recordEditForm>
    </div>
</aura:component> 
UnsavedChangesComponentDemoController
({
    handleDataChange : function(component, event, helper) {
        helper.dataChange(component, event, helper); 
    },

    handleSubmit : function(component, event, helper) {
        helper.submitData(component, event, helper); 
    },

    handleSave : function(component, event, helper) {
        helper.submitData(component, event, helper); 
    },

    handleDiscard : function(component, event, helper) {
        // similar to the handleSave method, but for discarding changes
    },

    handleSuccess : function(component, event, helper) {
        helper.handleSuccess(component, event, helper);
    }
})

UnsavedChangesComponentDemohelper
({
    dataChange : function(component, event, helper) {
        var unSavedChange = component.find('unsaved');
        unSavedChange.setUnsavedChanges(true, { label: 'You have unsaved changes. Do you want to Continue?' });
    },

    submitData : function(component, event, helper) {
        var unSavedChange = component.find('unsaved');
        unSavedChange.setUnsavedChanges(false);
    },

    handleSuccess : function(component, event, helper) {
        var record = event.getParams().response;

        component.find('notifLib').showToast({
            "variant": "success",
            "title": record.fields.Name.value,
            "message": "The record has created successfully."
        });
    }
})

Demo

Happy Learning!!!

Monday, January 21, 2019

Show Toast messages in Visualforce pages

This post explains how to fire toast messages from visualforce page.
In spring 19 release salesforce introduces the sforce.one.showToast({toastParams}) function in sforce.one object.
by using the function you can show different severity like success, error, info, warning.
Note: The change applies to Lightning Experience, Lightning communities, and all versions of the mobile app.
Example:
VF page
<apex:page lightningStylesheets="true">
    <script>
        function showToast() {
            sforce.one.showToast({
                "title": "Success!",
                "message": "Welcome to salesforce code crack.",
                "type": "success"
            });
        }
    </script>
    <apex:form >
        <apex:page >
            <apex:commandButton value="Show Toast" onclick="showToast();" />
        </apex:page>
    </apex:form>
</apex:page>
Enable the Available for Lightning Experience, Lightning Communities, and the mobile app permission.
Check below screenshot
once you enable the checkbox, add the visualforce page in salesforce mobile navigation
Demo

Happy Learning!!!

Saturday, January 19, 2019

How to create Popup/Modal box in Salesforce Lightning Web Components

This post explains how to create Popup/Modal Box in Lightning Web components
What is Modal Box?
A modal dialog is a window that forces the user to interact with it before they can go back to using the parent application.

Example

LWCModalBoxDemo.html

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

        <template if:true={openmodel}>
        <div class="demo-only" style="height: 640px;">
            <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">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" variant="neutral" onclick={closeModal}></lightning-button>&nbsp;&nbsp;&nbsp;&nbsp;
                        <lightning-button label="Save" variant="brand" onclick={saveMethod}></lightning-button>
                    </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
        </div>
        </template>
    </div>
</template>

LWCModalBoxDemo.js

import { LightningElement, track } from 'lwc';

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

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

Result

Happy Learning!!!

Friday, January 18, 2019

How to import Current User id in Lightning Web Components(lwc)

This post explains the how to import current user id in lightning web components
To import current user id we use the @salesforce/user/Id scoped module.

Syntax

import userId from '@salesforce/user/Id';

Example
LWCCurrentUserIdDemo.html
<template>
    <lightning-card title="CurrentUserId" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            <p>User Id:</p>
            <b>{userId}</b>
        </div>
    </lightning-card>
</template>

LWCCurrentUserIdDemo.js
import { LightningElement } from 'lwc';
import Id from '@salesforce/user/Id';
export default class LWCCurrentUserIdDemo extends LightningElement {
    userId = Id;
}

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

Happy Learning!!!

Wednesday, January 9, 2019

Apex snippets in Visual Studio Code

This post explains about how to add apex user snippets and how to use snippets in visual studio code

snippets are templates that make it easier to enter repeating code patterns, such as loops or conditional statements.

How to create snippets

Path: File > Preferences > user snippets
then select your language.json file

then enter your snippets in JSON file 

Ex: 
"List_Apex": {
 "prefix": "list<",
 "body": [
  "list<${1:object}> ${2:lstName} = new list<${1}>();"
 ],
 "description":"List of sObjects"
},
List_Apex: is the snippet name, you can enter your snippet name
prefix: defines how this snippet is selected from IntelliSense and tab completion.
body: is the content and either a single string or an array of strings of which each element will be inserted as a separate line.
description: description of your snippet(it is optional).

The example above has two placeholders, ${1:object} and ${2:lstName}. You can quickly traverse them in the order of their number. The string after the number and colon is used as an initial default.

you can make the editor cursor move inside a snippet. Use $1, $2 to specify cursor locations. The number is the order in which tabstops will be visited, whereas $0 denotes the final cursor position.
$1 indicates the first tab stop.

Examples

I created few snippets in the apex, 
{
 //For  List
"List_Apex": {
 "prefix": "list<",
 "body": [
  "list<${1:object}> ${2:lstName} = new list<${1}>();"
 ],
 "description":"List of sObjects"
},

// for set
"Set_Apex": {
 "prefix": "set<",
 "body": [
  "set<${1:object}> ${2:setName} = new set<${1}>();"
 ],
 "description":"Set of sObjects"
},

// for map
"Map_Apex": {
 "prefix": "map<",
 "body": [
  "map<${1:object}, ${2:object}> ${3:mapName} = new map<${1}, ${2}>();"
 ],
 "description":"Map of sObjects"
},

// for each loop
"For_Loop_Apex": {
 "prefix": "for",
 "body": [
  "for (${2:element} ${3:iteratorName} : ${1:array}) {",
  "\t$0",
  "}"
 ],
 "description": "For Loop"
},

// if condition
"if_cond_Apex": {
 "prefix": "if",
 "body": ["if ($1) {\n    $0\n}"],
 "description": "if statement for apex"
  },
 
 // soql apex
"soql_Apex": {
 "prefix": "soql",
 "body": ["list<$1> $2 = [SELECT $3 $0 FROM $1];"],
 "description": "SOQL query assignment to List variable"
},

}
Happy Learning!!!!

Tuesday, January 8, 2019

How to check Org Limits values using Apex?

This post explains How to check org limits values using Apex.
in Spring'19 release salesforce introduces the System.OrgLimit and System.OrgLimits
System.OrgLimits getAll and getMap methods to obtain either a list or a map of all your org limits. To get details on each limit, use instance methods from System.OrgLimit.

if you want to check total org limits using Workbench check below post  https://www.salesforcecodecrack.com/2018/09/how-to-check-your-org-governor-limits.html
if you want to check total org limits using REST API check below link
https://www.salesforcecodecrack.com/2018/10/governor-limits-Using-REST-API.html

How to know Org Limit Names

if you want limit names to check values(max and usage values),  check below sample code it shows limit names.
execute below sample code from the anonymous window  
List<System.OrgLimit> limits = OrgLimits.getAll();
for (System.OrgLimit aLimit: limits) {
    System.debug('Limit Name  ' + aLimit.getName());
}
OR
List<System.OrgLimit> limits = OrgLimits.getAll();
for (System.OrgLimit aLimit: limits) {
    System.debug('Limit Name  ' + aLimit.getName());
}
Result

Getting the org limit values

to get the maximum value and the current value of an org limit.
use below sample code 
in this example, I am getting MassEmail limit and DailyWorkflowEmails limits, you can check any limit based on your requirement.
sample code
Map<String,System.OrgLimit> limitsMap = OrgLimits.getMap();
System.OrgLimit workFlowLimit = limitsMap.get('DailyWorkflowEmails');
System.OrgLimit massEmailLimit = limitsMap.get('MassEmail');

// Max and ussage limit values of workFlowLimit
System.debug('Usage Value: ' + workFlowLimit.getValue());
System.debug('Maximum Limit: ' + workFlowLimit.getLimit());

// Max and ussage limit values of MassEmail
System.debug('Usage Value: ' + massEmailLimit.getValue());
System.debug('Maximum Limit: ' + massEmailLimit.getLimit());
Result
Happy Learning!!!

Monday, January 7, 2019

How to call apex class from lightning web components(lwc)

This post explains how to invoke an apex from lightning web components.
to import apex class methods we use @salesforce/apex scoped module

Syntax

import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';
apexMethod —>The imported symbol that identifies the Apex method.
Classname —> The name of the Apex class.
Namespace —> The namespace of the Salesforce organization.
Ex:
import getAccounts from '@salesforce/apex/LWCControllerTest.getAccounts'
import saveAccount from '@salesforce/apex/LWCControllerTest.saveAccount'

Demo

LWCApexMethodDemoController.cls
public inherited sharing class LWCApexMethodDemoController {
    @AuraEnabled(Cacheable = true)
    public static List<Account> getAccounts(){
      return [SELECT Id, Name, Phone, AccountNumber, Industry, CreatedDate FROM Account ORDER BY createddate DESC  Limit 10];
    }
}

LWCApexMethodDemo.html
<template>
    <div class="slds-theme_default">
      <center>
        <p style="font-size:medium;font-family:sans-serif;padding:10px;margin:5px">Invoke Apex Method Demo</p>
        <lightning-button label="getAccounts" variant="brand" icon-name="standard:account" onclick={getallaccounts}></lightning-button>
      </center><br/><br/>

      <template if:true={Accounts}>
        <table class="slds-table slds-table_cell-buffer slds-table_bordered">
          <thead>
            <tr class="slds-line-height_reset">
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="S.No">S.No</div>
              </th>
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="Account Name">Account Name</div>
              </th>
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="Phone">Phone</div>
              </th>
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="AccountNumber">AccountNumber</div>
              </th>
              <th class="slds-text-title_caps" scope="col">
                <div class="slds-truncate" title="Industry">Industry</div>
              </th>
            </tr>
          </thead>
          <tbody>
            <template for:each={Accounts} for:item="acc" for:index="indexvar">
              <tr class="slds-hint-parent" key={acc.id}>
                <td data-label="S.No">
                  <div class="slds-truncate" title={indexvar}>{indexvar}</div>
                </td>
                <td data-label="Account Name">
                  <div class="slds-truncate" title={acc.Name}>{acc.Name}</div>
                </td>
                <td data-label="Account Name">
                  <div class="slds-truncate" title={acc.Phone}>{acc.Phone}</div>
                </td>
                <td data-label="Account Name">
                  <div class="slds-truncate" title={acc.AccountNumber}>{acc.AccountNumber}</div>
                </td>
                <td data-label="Account Name">
                  <div class="slds-truncate" title={acc.Industry}>{acc.Industry}</div>
                </td>
              </tr>
            </template>
          </tbody>
        </table>
      </template>
    </div>
  </template>

LWCApexClassDemo.js
import {LightningElement, api, track} from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent'; // import toast message event .

// import apex class and it's methods. 
import getAccounts from '@salesforce/apex/LWCApexMethodDemoController.getAccounts'

export default class LWCApexMethodDemo extends LightningElement {

    @track Accounts; // return Accounts from apex class.
    @api Account;
    @track error; // to show error message from apex controller.
    @track success; // to show succes message in ui.
    // method for get  accounts.
    getallaccounts() {
        getAccounts()
            .then(result => {
                this.Accounts = result;
                this.error = undefined;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: ' Accounts Retrieve successfully',
                        message: 'Accounts Retrieve success, no of records-->' + result.length,
                        variant: 'success',
                    }),
                );
            })
            .catch(error => {
                this.error = error;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error while getting Accounts',
                        message: error.message,
                        variant: 'error',
                    }),
                );
                this.accounts = undefined;
            });
    } 
}
LWCApexClassDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="LWCApexMethodDemo">
    <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Result
Happy Learning!!!

Sunday, January 6, 2019

How to access Custom Labels in Lightning Web Components(lwc)

What is a Custom Label?
 Custom labels are text values stored in Salesforce that can be translated into any language that Salesforce supports. Use custom labels to create multilingual applications that present information (for example, help text or error messages) in a user’s native language.

To import Custom Labels we use @salesforce/label scope module in Lightning Web Components

Syntax

import labelName from '@salesforce/label/labelReference';
labelName  ---> it is a name that refers to the label.
labelReference ---> The name of the label in your org in the format namespace.labelName
Note:
if you don't have any namespace in your org use default namespace c
Ex: c.labelReference

Example

CustomLabelDemo.html
<template>
    <lightning-card  title="Custom Label Example" variant="narrow" icon-name="standard:opportunity">
        <p>{label.WelcomeLabel}</p>
    </lightning-card>
</template>
CustomLabelDemo.js
import { LightningElement } from 'lwc';

// importing Custom Label
import WelcomeLabel from '@salesforce/label/c.SalesforceCodeCrack';
export default class CustomLabelDemo extends LightningElement {
    label = {
        WelcomeLabel,
    };
}
CustomLabelDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="CustomLabelDemo">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Result

Happy Learning!!!

Saturday, January 5, 2019

How to access Static Resources in Lightning Web Components(lwc)


This post explains how to access static resources in Lightning Web Components.

To import static resources we use the @salesforce/resourceUrl scoped module.
Static Resources can be archives (such as .zip and .jar files), images, style sheets, JavaScript, and other files.

Syntax

import myResource from '@salesforce/resourceUrl/resourceReference';
myResource  ---> it is a name that refers to the static resource.
resourceReference ----> The name of the static resource in your Org.

Note:
If you are accessing managed package resource use namespace__managedResourceReference
namespace —> The namespace of the static resource.
managedResourceReference —>The name of the static resource in a managed package.

Example

in this example, I am uploading two resources one is .zip file and another file is a .jpg file.
.zip file contains another folder images in that folder we have two images.
StaticResourceDemo.html
<template>
    <lightning-card title="Static Resource Example" icon-name="custom:custom19">
        <div class="slds-m-around_medium">
            <img src={Sfdcimage1}>
            <img src={Sfdcimage2}>
            <img src={winterstricker}>
        </div>
    </lightning-card>
</template>

StaticResourceDemo.js
import { LightningElement } from 'lwc';
import TrailHead_Image from '@salesforce/resourceUrl/trailheadphoto';
import SFDC_Images from '@salesforce/resourceUrl/SFDCImages';
export default class StaticResourcesDemo extends LightningElement {
    Sfdcimage1 = SFDC_Images + '/images/winterstcikers.png';
    Sfdcimage2 = SFDC_Images + '/images/trailhead.png';
    winterstricker = TrailHead_Image;
}

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