Wednesday, December 21, 2022

All SLDS-BOX have an equal height using Flexbox in LWC

 



HTML

<ul class="list slds-p-around_large" >

<li class="list-item slds-box slds-box_xx-small slds-p-horizontal_large">
<div class="list-content">
<img src={xyz1} >
<div>
Header1
</div>
<p>
SubHeading 1
</p>
<lightning-button label="View" onclick={handleView} class="slds-float_left">
</lightning-button>
</div>
</li>

<li class="list-item slds-box slds-box_xx-small slds-p-horizontal_large">
<div class="list-content">
<img src={xyz2} >
<div>
Header2
</div>
<p>
SubHeading 2
SubHeading 2
SubHeading 2
SubHeading 2
</p>
<lightning-button label="View" onclick={handleView} class="slds-float_left">
</lightning-button>
</div>
</li>
</ul>

CSS

.list {
display: flex;
flex-wrap: wrap;
}

@media all and (min-width: 30em) {
.list-item {
width: 30%;
}
}

.list-item {
display: flex;
padding: 0.5em;
margin: 12px 18px 12px 18px;
}

.list-content {
display: flex;
flex-direction: column;
padding: 1em;
width: 100%;
}

.list-content p {
flex: 1 0 auto;
text-align: justify;
}

.list-content img {
width: 400px;
height: 300px
}


Friday, December 9, 2022

Get Salesforce instance URL in Apex (Salesforce)


URL Class

Represents a uniform resource locator (URL) and provides access to parts of the URL. Enables access to the base URL used to access your Salesforce org.

getOrgDomainUrl() 

Returns the canonical URL for your org.
For example, https://MyDomainName.my.salesforce.com.

String orgDomainUrl=System.URL.getOrgDomainUrl().toExternalForm();
System.debug(orgDomainUrl);

getSalesforceBaseUrl() 

Returns the URL of current connection to the salesforce org.
For example, https://MyDomainName.my.salesforce.com or 
https://MyDomainName.lightning.force.com

String baseUrlSalesforce=System.URL.getSalesforceBaseUrl().toExternalForm();
System.debug(baseUrlSalesforce);

The following example creates a link to a Salesforce record. The full URL is created by concatenating the Salesforce base URL with the record ID.

Account acct = [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1];
String fullRecordURL = System.URL.getSalesforceBaseUrl().toExternalForm() + '/' + acct.Id;

getCurrentRequestUrl() 

Returns the URL of an entire request on a salesforce Instance.
An example of a URL for an entire request is
https://yourInstance.salesforce.com/apex/myVfPage.apexp

String currentUrlSalesforce=System.URL.getCurrentRequestUrl().toExternalForm();
System.debug(currentUrlSalesforce);

// Get the query string of the current request.
System.debug('Query: ' + System.URL.getCurrentRequestUrl().getQuery());

Thursday, December 8, 2022

How To Redirect Your Users When Flows Finish (retURL)

 


To redirect users to a specific page in Salesforce after they click Finish:

/flow/flowName?retURL=url

For example: Redirect to Account Home Page

/flow/myFlow?retURL=001/o 

URL Options

You can't redirect flow users to a URL that’s external to your Salesforce org.

REDIRECT DESTINATIONRELATIVE URL (url)EXAMPLE
Chatter_ui/core/chatter/ui/ChatterPage_ui/core/chatter/ui/ChatterPage
Home pagehome/home.jsphome/home.jsp
List viewobjectCode?fcf=listViewId006?fcf=00BD0000005lwec
Object home page, such as Accounts homeobjectCode/o001/o
Specific record, such as a contact, report, dashboard, user, profile, or Chatter postrecordId0D5B000000SKZ7V
Visualforce pageapex/pageNameapex/myVisualforcePage


Use Lightning Web Components in External Website

 


In this blog, we'll look at how to use Lightning Web Components (LWC) on a public website. I'll walk you through each step so you can use it without any problems.

First, develop a Lightning Web Component that will be accessible without requiring a login. Insert the necessary markup into the Lightning Web Component. Here if you see the LWC html we have a property {recId}, we are going to pass this value from the URL. Which we will see in the later steps.

examspagelwc.html

<template>
<lightning-card>
Hi <b> {recId} </b>
</lightning-card>
</template>

examspagelwc.js

import { LightningElement } from 'lwc';

export default class Examspagelwc extends LightningElement {
recId;

connectedCallback() {
const param = 'id';
this.recId = this.getUrlParamValue(window.location.href, param);
}

getUrlParamValue(url, key) {
return new URL(url).searchParams.get(key);
}
}

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

To make it available to the whole public, we must implement the ltng:allowGuestAccess interface.

quizapp.app
<aura:application extends="ltng:outApp" access="global" implements="ltng:allowGuestAccess" >
<aura:dependency resource="c:examspagelwc"/>
</aura:application>
exampagevf.page
<apex:page showHeader="false" sidebar="false">
<apex:includeLightning /> <!--<apex:includeScript value="/lightning/lightning.out.js" />-->

<script>
$Lightning.use("c:quizapp", function() {
$Lightning.createComponent("c:examspagelwc",
{
},"new",
function(cmp) {
console.log('LWC Componenet added in VF page');
});
});
</script>
<div id="new"></div>
</apex:page>

Go to Setup
From Sites and Domains, Select sites
Click on NEW
Give the Site Label
For Active site home page click on lookup and select your VF Page
Then click Save button AND Activate the site.

Now copy the the site url and pass the parameter that we are passing in lwc js to show it in our lwc html.

For example:
if site URL is:- https://2022quizapp-developer-edition.ap26.force.com/

then we need id to pass in the url. so our url look like this:
https://2022quizapp-developer-edition.ap26.force.com/?id=201

So when we open this url, our LWC will show Hi 201



Tuesday, November 8, 2022

Create Quick Actions with Lightning Web Components

 


To set up a Lightning web component as a quick action on a record page, define the metadata in <component>.js-meta.xml

Define a lightning__RecordAction target and  specify actionType as ScreenAction for a screen action that opens in a window or Action for a headless action that executes when clicked.

callLwc.html

<template>
</template>

callLwc.js

import { LightningElement,api,track } from 'lwc';
import {ShowToastEvent} from 'lightning/platformShowToastEvent'

export default class CallLwc extends LightningElement {
@api recordId;

@api invoke(){
alert('Record Id is: '+this.recordId;
}

callLwc.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordAction</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordAction">
<actionType>Action</actionType>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>

To Create Quick Action:

As we are creating this action for the Contact Record Page, it is an object-specific action.

  • Navigate to the Contact Object  in Setup.
  • Under Button, Links, and Actions.
  • Create a new Action.
  • Select LWC as Action Type.
  • Select your LWC component 
  • Give label to your Action
  • Name will be auto Populated
  • Click Save Button
  • Edit the Page Layout, and select Mobile & Lightning Actions
  • Drag the new Quick Action to the Lightning Experience Actions section 
  • You might have to override the standard actions before you’re able to add custom actions 

If you have any comments or queries about this, please feel free to mention them in the comments section below.

Testing HTTP Callouts by Implementing the HttpCalloutMock Interface in Salesforce


This is a full example that shows how to test an HTTP callout. 

CalloutClass

====================

public class CalloutClass {
public static HttpResponse getInfoFromExternalService() {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/example/test');
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
return res;
}
}


JSON2ApexMock Apex Class

==============================

 @isTest

global class JSON2ApexMock implements HttpCalloutMock {

HttpResponse res;
global JSON2ApexMock(HttpResponse r)
{
res=r;
}
global HttpResponse respond(HttpRequest req){
return res;
}
}


Callout Test Class
=====================================
@isTest
private class CalloutClassTest {
@isTest static void testCallout() {

// Create a fake response
HttpResponse res=new HttpResponse();
res.setBody('{"Description": "200"}');
res.setHeader('Content-Type', 'application/json;charset=UTF-8');
res.setStatusCode(200);

// Set mock callout class
Test.setMock(HttpCalloutMock.class, new JSON2ApexMock(res));
// Call method to test.
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
HttpResponse res = CalloutClass.getInfoFromExternalService();
// Verify response received contains fake values
String contentType = res.getHeader('Content-Type');
System.assert(contentType == 'application/json');
String actualValue = res.getBody();
String expectedValue = '{"Description":"200"}';
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, res.getStatusCode());
}
}


If you have any comments or queries about this, please feel free to mention them in the comments section below.

Download Files from Salesforce in zip format at once

 

In certain situations, we may need to download many files from Salesforce at once.

Simple URL hack:
By including the file's content version Ids in the URL, you may download all files in a zip archive. Everyone remarked that it is not the preferred technique, and I may call it a URL hack.

Below is the URL format that you need to use:

https://tridentpvtltd.lightning.force.com/sfc/servlet.shepherd/version/download/068aaaaaaaaaa/0684bbbbbbbbR/068cccccccccc


You may get the files as zip files by simply pasting this URL.

Friday, September 30, 2022

Add a Property to each Object in an Array of Objects with JS in LWC

 


Hi Folks, In this blog we will try to understand, How we can Add a Property to each Object in an Array of Objects with JS in LWC.

Lets suppose we have an array as given below:-

let contactData=[
                   {Name:'Rahul',Age:'31',CreditScore:750},
                   {Name:'Rogers',Age:'28',CreditScore:640}
];

Now let takes a requirement, that if the credit score is more than or equals to 700 then the rating should be 'Hot' or if it is less than the 700 rating should be 'Cold' and then add this property to every object of the Array of Objects that we have. And final output will look like as given below:

[
   {Name:'Rahul',Age:'31',CreditScore:750,rating:'Hot'},
   {Name:'Rogers',Age:'28',CreditScore:640,rating:'Cold'}
]

To achieve this we can use either forEach method or map method. 

Using forEach:

let contactData=[
                   {Name:'Rahul',Age:'31',CreditScore:750},
                   {Name:'Rogers',Age:'28',CreditScore:640}
];
contactData.forEach(element=>{
if(element.CreditScore>=700)
{ element.rating='Hot'; }
else
{
element.rating='Cold'; }
});

console.log('Final Result is:- '+JSON.stringify(contactData));

     

Using map:

let contactData=[
                   {Name:'Rahul',Age:'31',CreditScore:750},
                   {Name:'Rogers',Age:'28',CreditScore:640}
];
let finaldata=contactData.map(x=>{
if(x.CreditScore>=700)
{ return {...x,rating:'Hot'}; }
else
{
return {...x,rating:'Cold'}; }
});

console.log('Final Result is:- '+JSON.stringify(finaldata));

Output in Cosole:-

[
   {"Name":"Rahul","Age":"31","CreditScore":750,"rating":"Hot"},
   {"Name":"Rogers","Age":"28","CreditScore":640,"rating":"Cold"}
]

If you have any comments or queries about this, please feel free to mention them in the comments section below.