Author Archives: Biswajeet

About Biswajeet

Biswajeet is my Name, Success is my Aim and Challenge is my Game. Risk & Riding is my Passion and Hard Work is my Occupation. Love is my Friend, Perfection is my Habit and Smartness is my Style. Smiling is my Hobby, Politeness is my Policy and Confidence is my Power.

Check Current User has a Custom Permission in Salesforce Using Apex

we can use FeatureManagement.checkPermission method, to determine which users have access to a specific custom permission.

Sample Code:

Boolean hasCustomPermission = FeatureManagement.checkPermission('YOUR_CUSTOM_PERMISSION_API_NAME');

Converting DateTime to Date in Salesforce

Solution 1: Create a date newInstance() and pass the Year, Month and Day from the dateTime.

DateTime dt = System.now();
Date d = Date.newInstance(dt.year(), dt.month(), dt.day());
System.debug('Print Date:' + d);

Solution 2: Get date from the DateTime using Date() method.

DateTime dt = System.now()
Date d = dt.date();
System.debug('Print Date:' + d);

Google reCAPTCHA in Lightning Component

Configure the Google reCAPTCHA and get the Site Key & Secret Key:

  • Login to Google reCAPTCHA
  • Register a new site
  • Add Label e.g. Salesforce.com
  • Select reCAPTCHA type “reCAPTCHA v2”
  • Select “I’m not a robot” Checkbox option.
  • Add a domain e.g. yourorgurl.com
  • Accept the reCAPTCHA Terms of Service
  • Submit and get the Site Key & Secret Key

Create a VF page to configure Google reCAPTCHA in it and we have to embed the VF page in our lightning component.

GoogleReCaptcha VF Page:

<apex:page sidebar="false" showHeader="false" standardStylesheets="false" cache="false" id="pg" applyBodyTag="false" applyHtmlTag="false">
    <html>
        <head>
            <script src='https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit' async='' defer=''/>
            <script type='text/javascript'>
                var verifyCallback = function(response){
                    parent.postMessage('VALID', 'https://biswajeet-dev-ed.lightning.force.com/');
                };
            
            var onloadCallback = function() {
                grecaptcha.render('reCAPTCHAWidget', {
                    'sitekey' : 'ADD_YOUR_GOOGLE_RECAPTCHA_SITE_KEY', 
                    'callback' : verifyCallback
                });
            };
            </script>
        </head>
        <body>
            <div id="reCAPTCHAWidget"></div>
        </body>
    </html>
</apex:page>

Embed the above created VF page in our lightning component to display Google reCAPTCHA.
Lightning Component:

<aura:component implements="flexipage:availableForAllPageTypes,force:appHostable,forceCommunity:availableForAllPageTypes" access="global">
    
    <!--Attributes-->
    <aura:attribute name="isDisable" type="Boolean" default="true"/>
    <aura:attribute name="firstName" type="String"/>
    <aura:attribute name="lastName" type="String"/>
    
     <!--Handlers-->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    
    <div class="slds-m-around--xxx-large slds-align_absolute-center" style="width:70%;">
        <fieldset class="slds-box slds-align_absolute-center" >
            
            <legend id="newform" class="slds-text-heading--small login-heading">
                Registration
            </legend>
            
            <lightning:input name="fName" label="First Name" value="{!v.firstName}"/>
            <br/>
            <lightning:input name="lName" label="Last Name"  value="{!v.lastName}"/>
            <br/>
            <iframe src="/apex/GoogleReCaptcha" scrolling="no" frameborder="0" width="100%" allowtransparency="true"></iframe>
            
            <div class="slds-align_absolute-center">
                <lightning:button onclick="{!c.handleSubmit}" disabled="{!v.isDisable}" variant="brand" name="btnSubmit" label="Submit"   />
            </div>
        </fieldset>
    </div>
</aura:component>

Lightning JS Controller:

({
    doInit : function(component, event, helper) {
        var vfURL = 'https://biswajeet-dev-ed.lightning.force.com/';
        window.addEventListener('message', function(event){
            if(event.origin !== vfURL){
                return;
            }
            if(event.data === 'VALID'){
                component.set('v.isDisable', false); 
            }
        }, false);
    },
    
    handleSubmit : function(component, event, helper) {
        
    },
})

Salesforce Web to Lead form with Google reCAPTCHA

Configure the Google reCAPTCHA and get the Site Key & Secret Key:

  • Login to Google reCAPTCHA
  • Register a new site
  • Add Label e.g. Salesforce.com
  • Select reCAPTCHA type “reCAPTCHA v2”
  • Select “I’m not a robot” Checkbox option.
  • Add a domain e.g. yourorgurl.com
  • Accept the reCAPTCHA Terms of Service
  • Submit and get the Site Key & Secret Key

Remote Site Settings:
Create Remote Site settings for google.com site URL

Note: Make sure your org “Show Quick Create” is enabled.
Go to Setup | User Interface | Select the checkbox of “Show Quick Create” | Click on Save button at the bottom.

Setup Web-to-Lead:

1. Go to Setup | Leads | Web-to-lead | Select the checkbox of “Web-to-Lead Enabled” | Select the checkbox of “Require reCAPTCHA Verification” | Select Default Lead Creator | Click on Save button at the bottom.

2. Click on “Create Web-to-Lead Form” button | Select Lead fields you want to add on the form | Give the redirect URL | Click the lookup icon to select “reCAPTCHA API Key Pair”.

3. In the popup window, Click on the New Button | Enter the “API Key Pair Nickname” of your choice | Enter Google reCAPTCHA Site Key | Enter Google reCAPTCHA Secret Key | Click on Save.

4. Click on Generate button, and you will get the HTML code ready to put on your website.

Web-to-Lead Form:

Assign a Default Community to a User Profile Programmatically

Salesforce stores default community to a User Profile in NetworkAffinity object. Using apex we cannot insert the default community to a User Profile. We can make a REST API call to add default community to a User Profile.

Sample Code:

//Get Endpoint URL
String endpointURL = URL.getSalesforceBaseUrl().toExternalForm()+'/services/data/v48.0/sobjects/NetworkAffinity';
HttpRequest req = new HttpRequest();  
req.setEndpoint(endpointURL);  
req.setMethod('POST');
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionId()); 
req.setHeader('Content-Type', 'application/json;charset=UTF-8');
//Add Community Id as NetworkId and Profile/Permission Id
req.setBody('{"NetworkId":"0DB1I000000TP59WAG","ProfileId":"00e1I000001uXJUQA2"}');
Http http = new Http();
HttpResponse response = http.send(req);
System.debug('response-' + response);

Note: Add your salesforce base URL as remote site settings and then execute above code in developer console anonymous window.