Sunday, December 30, 2018

Use of Inherited Sharing in Apex Class


This post explains the use of inherited sharing in apex class
If you specify inherited sharing Keyword on an Apex class,  which allows the class to run in the sharing mode of the class that called it. Using inherited sharing enables you to pass security review and ensure that your privileged Apex code is not used in unexpected or insecure ways.

  1. An Apex class with inherited sharing runs as with sharing when used as a Visualforce page controller, Apex REST service, or an entry point to an Apex transaction.
  2. An Apex class with Inherited Sharing is being called from some other class which is having without sharing setting, then it will run in without sharing mode.
Example
This example declares an Apex class with inherited sharing and a Visualforce invocation of that Apex code. Because of the inherited sharing declaration, only opportunities for which the running user has sharing access are displayed. If the declaration is omitted, even opportunities that the user has no rights to view are displayed due to the insecure default behavior of omitting the declaration.
Apex Class
public inherited sharing class OpportunityMethods {
    public list<Opportunity> getAllTheOpps(){
        return [SELECT Id, Name, StageName FROM Opportunity];
    }
}
Visualforce page
<apex:page controller="OpportunityMethods">
    <apex:repeat value="{!getAllTheOpps}" var="record">
        {!record.Name}
    </apex:repeat>
</apex:page>

Happy Learning!!

Saturday, December 29, 2018

How to Enforce Field-Level Security Permissions for SOQL Queries?


This post explains how to enforce field level security permissions for SOQL queries,
In Spring' 19 release salesforce introducing this feature, at the time of writing this post this feature in Beta stage.
Use the WITH SECURITY_ENFORCED clause to enable checking for the field- and object-level security permissions on SOQL SELECT queries, including subqueries and cross-object relationships. Although performing these checks was possible in earlier releases, this clause substantially reduces the verbosity and technical complexity in query operations.

How it Works?

If fields or objects referenced in the SELECT clause using WITH SECURITY_ENFORCED are inaccessible to the user, an exception is thrown, and no data is returned.

Example: 1
SELECT Id, Name, StageName, ClosedDate FROM Opportunity WITH SECURITY_ENFORCED
if the stage name is inaccessible to the user it throws an exception insufficient permissions. and no data return.

Example: 2
SELECT Id, (SELECT FirstName, LastName FROM Contacts), (SELECT Description, StageName, CloseDate FROM Opportunities) 
       FROM Account WITH SECURITY_ENFORCED
if the First Name, stage name is inaccessible to the user it throws an exception insufficient permissions. and no data return.

Resource
http://releasenotes.docs.salesforce.com/en-us/spring19/release-notes/rn_apex_select_with_security_enforced.htm

Wednesday, December 26, 2018

How to remove all special characters from String in Apex

This post explains how to remove special characters from the string in Apex
Example:
String strText = 'Welcome - to! % $sale&sforce \\ /code # crack %';
strText = strText.replaceAll('[^a-zA-Z0-9\\s+]', '');
System.debug('strText ======> '+strText);

Result
Happy Learning!!!

Sunday, December 23, 2018

How to get Record Type Developer Name in Apex?


This post explains how to get the record type developer name in the apex.

Getting Record Type Id using Developer Name

Let assume Record Type Developer Name  is "Customer_Account" on Account Object
you want id of the Record type use below sample code

Example

Id idRecordId = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Customer_Account').getRecordTypeId();
System.debug('RecordTypeId based on Developer Name ---> '+idRecordId);
the above code returns the Record type Id based on developer name

Getting Record Type Developer Name

Let assume Record Type Name  is "Cluster Account" on Account Object
you want Developer Name of the Record type use below sample code

Example

String strRecordDevName = Schema.SObjectType.Account.getRecordTypeInfosByName().get('Cluster Account').getDeveloperName();
System.debug('Record Developer Name ====> '+strRecordDevName);
the above code returns the developer name based on the record type name
Assume you have record type id instead of name use below sample code
String strRecordDevName = Schema.SObjectType.Account.getRecordTypeInfosById().get('012w0000000kgdfAAQ').getDeveloperName();
System.debug('Record Developer Name ====> '+strRecordDevName);
Let us know if have any queries
Happy Learning!!!

Friday, December 21, 2018

How to get current Month last date in Apex?

This post explains how to get the current month last date in the apex.

Example:

Date dLastDate = Date.today().addMonths(1).toStartOfMonth().addDays(-1);
System.debug(' current month last date ===> '+dLastDate);

Result
Let us know if you have any queries
Happy Learning!!!

Wednesday, December 19, 2018

How to Read REST API GET Parameters in Apex

This post explains How we can read the REST API GET parameters in Apex
We can read the parameters based on URL

Example:1

URL: /services/apexrest/getContactdetails?accountId=Accountd&leadSource=Web
Rest Method: GET
Demo:
@RestResource(urlMapping='/getContactdetails/*')
global class RESTServiceDemoClass {
    
    @HttpGet
    global static list<Contact> getContactList() {
        String strAccId = '';
        String strLeadSource = '';
        list<Contact> lstCons;
        RestRequest restReq = RestContext.request;
        RestResponse restRes = RestContext.response;
        // Reading parametrs from URL
        strAccId = restReq.params.get('accountId');
        strLeadSource = restReq.params.get('leadSource');
        if(!String.isBlank(strAccId) && !String.isBlank(strLeadSource)) {
            lstCons = [Select Id, Name, Email FROM Contact WHERE AccountId =:strAccId AND LeadSource =: strLeadSource];
        }
        return lstCons;
    }
}
above class return the list of contacts based on passing parameters accountId and lead source
Example URL
/services/apexrest/getContactdetails?accountId=0017F00000idCUi&leadSource=Web
Result:

Example: 2

URL: /services/apexrest/getContactdetails/Accountd&Web
Rest Method: GET

Demo:
@RestResource(urlMapping='/getContactdetails/*')
global class RESTServiceDemoClass {
    
    @HttpGet
    global static list<Contact> getContactList() {
        String strAccId = '';
        String strLeadSource = '';
        list<Contact> lstCons;
        RestRequest restReq = RestContext.request;
        RestResponse restRes = RestContext.response;
        // Reading parametrs from URL
        strAccId = restReq.requestURI.substring(restReq.requestURI.lastIndexOf('/') + 1);
        strAccId = strAccId.left(strAccId.lastIndexOf('&'));
        strLeadSource = restReq.requestURI.substring(restReq.requestURI.lastIndexOf('&') + 1);
        if(!String.isBlank(strAccId) && !String.isBlank(strLeadSource)) {
            lstCons = [Select Id, Name, LeadSource FROM Contact WHERE AccountId =:strAccId AND LeadSource =: strLeadSource];
        }
        return lstCons;
    }
}

Example URL:
/services/apexrest/getContactdetails/0017F00000idCUi&Web
Result:



Let Us know if you have any queries.
Happy Learning!!

Sunday, December 16, 2018

Introduction to Lightning Web Components(LWC)


This post explains the
1. What is Lighting Web Component(LWC)?
2. How to Create a Lightning Web Component with Non-scratch org.

What is Lighting Web Component(LWC)?
1. LWC is a new Programming Language modal for building a Lightning Components
2. LWC uses modern web programming standards, shadow DOM, modules and ECMAScript7.
3. LWC coexist and interoperate with the original Aura programming model, and delivers unparalleled performance.
How to Create a Lightning Web Component?
You cannot create LWC directly from your developer console. you need to SFDX to create your lightning web component.

Step 1: Steps to set up an SFDX with vs code

1. Download and Install Salesforce CLI
2. Download vs code From this link and install.
Note: Once install the Salesforce CLI You can verify using below command
sfdx --version

Installing Salesforce Extensions in vs code
1. Open vs code install Salesforce extension pack

2. Install Lightning Web Components Extension

Step 2: Signup to pre-release org

Sign up for a pre-release Developer Edition Org using below link
Note: Once you create the Pre-release developer org add my domain for the Org otherwise custom developed components are not visible in the app builder

Step 3: Upgrade Pre-Release version of Salesforce CLI

Use below command to upgrade the Pre-release version of Salesforce CLI
sfdx plugins:install salesforcedx@pre-release

Step 4: Creating the SalesforceDx Project

Go to your vs code editor
Press "CTRL + SHIFT + P" then select SFDX:Create Project with Manifest

Enter project Name and Select Folder

Step 5: Authorize an org

Press "CTRL + SHIFT + P" then select SFDX: Authorize an Org
this command opens your default browser then login to your pre-release developer org
once logged in to your org you may close your browser

Step 6: Creating Lightning Web Components

Press "CTRL + SHIFT + P" then select SFDX: Create Lightning Web Component
Then Select Folder where you want to save your LWC component
Then give your component name
verify component under lwc folder


Example

LWCDemoComponent.html
<template>
    <lightning-card title="Contact" icon-name="standard:contact">

        <lightning-record-form object-api-name={objectApiName} record-id={recordId} 
                               fields={fields}></lightning-record-form>

    </lightning-card>
</template>
LWCDemoComponent.js
import { LightningElement , api, track} from 'lwc';

export default class LWBDemoComponent extends LightningElement {
    @api recordId;
    @api objectApiName;
    @track fields = ['Name', 'Title', 'Phone', 'Email'];
}
LWCDemoComponent.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="LWBDemoComponent">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
      <targets>
    <target>lightning__AppPage</target>
    <target>lightning__RecordPage</target>
    <target>lightning__HomePage</target>
  </targets>
</LightningComponentBundle>

Step 7: Deploy your component in Org

once you complete the code, go to your lwc folder then right click on the component folder
select SFDX: Deploy Source to Org
go to contact record page editor you can verify your components
That's it

Resources
Trailhead Link

Let us know if you have any queries
Happy Learning!!!

Sunday, December 9, 2018

lightning:fileUpload component in lightning

This post explains how to use lightning:fileupload in lighting component

lightning:fileUpload component provides an easy and integrated way for users to upload multiple files. The file uploader includes drag-and-drop functionality and filtering by file types.

Limitations
  • By default we can upload max 10 files, Admins can contact Salesforce to request a changeup to a maximum of 25 files uploaded at one time
  • The maximum file size we can upload is 2 GB.
  • Guest users can't add files to Communities
Note:
1. This component is not supported in Lightning Out or standalone apps.
2. we can't upload files with the following file extensions: .htm, .html, .htt, .htx, .mhtm, .mhtml, .shtm, .shtml, .acgi, .svg
File Uploder Example
FileuploaderComponent
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    
    <lightning:notificationsLibrary aura:id="notifLib"/>
    <div class="slds-theme_default">
        <lightning:fileUpload title="Upload Files"
                              name="fileuploader"
                              label="Upload Files"
                              recordId="{!v.recordId}"
                              multiple="true"
                              accept=".pdf,.png,.jpg"
                              onuploadfinished="{!c.afterFinish}"/>
    </div>
    
</aura:component>
FileUploaderComponentController.js
({
    afterFinish : function(component, event, helper) {
        //  Geting the list of uploaded files
        var uploadFiles = event.getParam("files");
        
        var strFileNames = '';
        
        // getting uploaded file names
        for(var i=0; i<uploadFiles.length; i++) {
            strFileNames += uploadFiles[i].name + ', ';
        }
        
        // Showing Success message
        component.find("notifLib").showToast({
            "variant": "success",
            "title": strFileNames,
            "message": uploadFiles.length + " Files are Uploaded Successfully!"
        });
        $A.get("e.force:refreshView").fire();
    }
})
Demo

Let us Know if you have any queries
Happy Learning!!

Saturday, December 8, 2018

How to add Recycle Bin tab in Lightning Experience?

This post explains how to add recycle bin tab in Lightning Experience

Currently, Recycle bin page not available in Lighting Experience, to overcome this we can directly access recycle page using web tabs, this is a small workaround
Note: we are directly accessing classic UI recycle page so we can't except the lightning look and feel to the page.

Demo:
Path
Go to setup ---> Tabs ----> Click new under web tabs
1st Page


2nd Page

Click Next
3rd Page


Click Next
Under “Button or Link URL” section, enter below URL
/search/UndeletePage

Click Next ----> Assign to desired profiles ----> Click Save
That's it.
Let us Know if you have any queries
Happy Learning


Monday, December 3, 2018

Show Modal box using lightning:overlayLibrary in Lightning component

This Post explains the how to show modal box using lightning:overlayLibrary

What is Modal?
1. Modal blocks everything else on the page until it’s dismissed.
2. Modal is triggered by user interaction, which can be a click of a button or link.
3. The modal header, body, and footer are customizable. Pressing the Escape key or clicking the close button closes the modal.

Demo:
OverlayLibrarydemoComponent
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <aura:attribute name="strRecId" type="String" />
    <lightning:overlayLibrary aura:id="overlayLibDemo"/>
    <div class="slds-theme_default">
        <p>
            <h1>Lightning OverlayLibrary Example</h1>
            <lightning:button variant="brand" label="Account Edit" title="Account Edit" onclick="{!c.showModal}" />
        </p>
    </div>
</aura:component>

OverlayLibrarydemoComponentController
({
 showModal : function(component, event, helper) {
  helper.showModalHelper(component, event, helper);
 }
})

OverlayLibrarydemoComponentHelper
({
    showModalHelper : function(component, event, helper) {
        var strAccId = component.get("v.recordId");
        console.log('Account Id ====>'+strAccId);
        $A.createComponent("c:AccountEditComponent", 
                           {strRecordId : strAccId},
                           function(result, status) {
                               if (status === "SUCCESS") {
                                   component.find('overlayLibDemo').showCustomModal({
                                       header: "Account Edit Form",
                                       body: result, 
                                       showCloseButton: true,
                                       cssClass: "mymodal", 
                                   })
                               }                               
                           });
    }
})

OverlayLibrarydemoComponent.css
.THIS {
    text-align: center;
    vertical-align: middle;
    line-height: 90px;  
    font-size: 20Px;
}

below component shows in the modal box  when clicking the button
AccountEditComponent
<aura:component implements="flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId,force:lightningQuickAction" access="global" >
    <aura:attribute name="strRecordId" type="String" />
    <lightning:overlayLibrary aura:id="overlayLibDemo1"/>
    <lightning:notificationsLibrary aura:id="notifLib"/>
    <div class="slds-theme_default">
        <lightning:recordEditForm aura:id="editform"
                                  onsubmit="{!c.handleSubmit}"
                                  onsuccess="{!c.handleSuccess}"
                                  recordId="{!v.strRecordId}"
                                  objectApiName="Account">
            <lightning:messages />
            
            <lightning:inputField fieldName="Name" aura:id="accName" />
            <lightning:inputField fieldName="Industry" />
            <lightning:inputField fieldName="Phone" />          
            <lightning:inputField fieldName="Type" />
            <div class="slds-m-top_medium">
                <lightning:button variant="brand" type="submit" name="save" label="Save" />
            </div>
        </lightning:recordEditForm>
    </div>
</aura:component>
AccountEditComponentController
({
    handleSubmit : function(component, event, helper) {
        component.find('editform').submit();
    },
    
    handleSuccess : function(component, event, helper) {
        var strAccName = component.find("accName").get("v.value");
        component.find('notifLib').showToast({
            "variant": "success",
            "title": strAccName,
            "message": "Account Updated Successfully!!"
        });
        component.find("overlayLibDemo1").notifyClose();
    },
})

Let us Know if you have any queries
Happy Learning!!