Tuesday, 31 August 2021

How to format number in Visualforce and in LWC ?

 Use Case - We want to show a number in percentage format, say if field value contains 15 then we need to show in UI as like 15%.

Here is the sample code for it.

<apex:outputLabel value="In-Network Copay Amount:" for="incper" style="color:#3E3E3C" >

        <apex:outputText value="{0, number, ###,##0}" id="myNumberDisplay" >

<apex:param value="{!Eligibility_Summary__c.In_Network_Copay_Percentage__c}"/>

</apex:outputText>%

 </apex:outputLabel>


 

LWC

<div class="slds-col slds-size_1-of-2">
   <label>In-Network Copay Amount</label>
   <div class="slds-col slds-size_1-of-1">
<lightning-formatted-number value={summary.In_Network_Copay_Percentage__c}>
</lightning-formatted-number>
     %
   </div>
</div>


Sunday, 29 August 2021

How to formart Date in Visualforce page ?

 We can format date as per our need, Lets assume we want show date as Aug 8, 2021.

 <apex:outputLabel value="Resident DOB:" for="doiv" style="color:#3E3E3C">

          <apex:outputText value="{0,date,MMM dd,yyyy}" id="inamsd" style="color:#080707">

               <apex:param value="{!Eligibility_Summary__c.Resident_DOB__c}" />

           </apex:outputText> 

 </apex:outputLabel>

How to show success message and error message in LWC?

1. First import ShowToastEvent 
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
2. Add below method.
showSuccess(){
        this.dispatchEvent(new ShowToastEvent({
          title: 'Success',
          message: 'Lead has been Cloned',
          variant: 'success',
        }));
    }

3. Call this.showSuccess(); where we want to show success message.
4. Error message
showError(msg){
        const evt = new ShowToastEvent({
            title: 'Eligibility Error',
            message: msg,
            variant: "error"
        });
        this.dispatchEvent(evt);
    }
5. Call from catch block to show error message
 .catch(err => {
                    console.log('error', err);
                    this.loading = false;
                    this.showError(err.body.message);
                });
if needed we can show generic error message instead of technical
error message.

Saturday, 28 August 2021

How to get record Id from URL to pass to another LWC component ?

 Use Case : On click of button on Lead record detail, you want to open popup and do some processing on that lead record.

1. Create Aura Component to wrap LWC component.

2. LWC component has all logic.

3. Create quick action button invoke Aura component.

Now how to pass record Id from URL to LWC component.

<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId">

<c:cloneLead recordId="{!v.recordId}"/>

</aura:component>

Note - After Winter 21 onwards, we don't have to warp lighting aura component for LWC. Because LWC started supporting quick actions such headless action and flow action. 


Friday, 27 August 2021

How to make hyperlink in trigger.addError message ?

 Use Case - On Lead conversion, we would want to mandate user to use existing account instead of creating new account .  For that we have written logic Account before trigger, if there is an existing records then show error message along with Record Link.


 for(Account account : accounts){

    String link = '<a href="https://yourdomain.lightning.force.com/'+ account.Id +'" target="_blank">'+ account.Name + '</a>';

         account.addError('Please choose Existing Account Record because there is an already existing Resident Record having same SSN '+link);


}

Wednesday, 25 August 2021

How to load huge test sample response for test class ?

 When we are writing test class for integration parsing class, The easiest way to for code coverage and validate is uploading sample response in static resource and retrieve in test class. Here is code snippet.

1. Create static resource upload text file containing response

StaticResource r = [SELECT Body FROM StaticResource WHERE Name = 'Static_ResourceName'];

        String jsonString = r.Body.toString();

Apexclass obj = Apexclass .parse(jsonString);

Friday, 20 August 2021

How to Create/Delete file attachments(Content Document) through Apex ?

 There are 3 standard salesforce objects to store file attachments.

Content Document, ContentDocumentVersion, ContentDocumentLink. 

Here is the article to talk about these objects and relationship. 

https://www.forcetalks.com/blog/contentdocument-and-contentversion-in-salesforce-an-overview/

ContentDocumentVersion

ContentDocumentLink






This post is all about how to create/delete content document though Apex. Here is code snippet

// Insert Content Version record
ContentVersion contentVersionRec = new ContentVersion(Title='filename',PathOnClient ='FileName.pdf',VersionData = bodyBlob,origin = 'H');
INSERT contentVersionRec; // this will insert one record in ContentDocument and ContentVersion ,ContentDocument  is parent and ContentVersion is child record

// get contentdocument id
contentVersionRec = [SELECT Id, Title, ContentDocumentId FROM ContentVersion WHERE Id = :contentVersionRec .Id LIMIT 1];

// Create Content Document Link record- This will attach file to particular record

 ContentDocumentLink contentlink = new ContentDocumentLink();
 contentlink.LinkedEntityId = 'Sobject Id'; // for example lead or opportunity record Id
 contentlink.contentdocumentid = contentVersionRec .contentdocumentid;
 contentlink.ShareType = 'I';
 contentlink.Visibility = 'AllUsers';
 INSERT contentlink;

Note - Same content document can be shared with other objects, we just have to create ContentDocumentLink records.

Deleting File Attachments

//Delete ContentDocumentLink
Delete [select id from ContentDocumentLink where contentdocument.Title = 'ES-0275' and LinkedEntityId = '00Q1Q00001IZxcAUAT'];

// Delete Content Version 
Delete[select id from ContentVersion where Title = 'ES-0275'];

// Delete Content Document
Detete[select id from ContentDocument where Title = 'ES-0275'];
Note - If we delete content document then contentdocumentversion and contentdocumentlink will be deleted automatically.




Friday, 13 August 2021

How to Populate Salesforce Lookup Using an External ID?

Having External ID defined in an object will be very very helpful for data integration.

We can also use External ID to populate Look up field in Apex. 

Lets assume we have two Object MedicationStatement and HealthCondition. MedicationStatement has look up field to HealthCondition. Here is the code how to populate look up field value without writing query.

Diagnosis__c - Look up field from MedicationStatement to HealthCondition

DiagnosisId__c - External Id of HealthCondition object


HealthCondition cond = new HealthCondition(DiagnosisId__c = 123);

MedicationStatement medstat = new MedicationStatement();

medstat.PatientId = '0012g00000bZiaFAAS'; - This is Account Id

medstat.Status = 'Active';

medstat.MedicationCodeId = '0iP2g0000004C93EAE';

medstat.Diagnosis__r = 123;

medstat.OrderID__c = 55;

Insert medstat;