Skip to main content

How to pass wrapper class object to LWC component from Apex method ?

 Use Case - We need to have validation in apex code if any of the information missed we need to throw error. First Name, Last Name, SSN or DOB etc. Assume we have opportunity Id as parameter, will query Account information and add into a wrapper class.

Public class ResidentDetailRequest {

    @AuraEnabled public Integer FacilityNumber;
    @AuraEnabled public String FacilityName; 
    @AuraEnabled public String LastName;
    @AuraEnabled public String FirstName; 
    @AuraEnabled public String MiddleName;
    @AuraEnabled public String SSN;
    @AuraEnabled public String DOB;
    @AuraEnabled public String Suffix;
}

Main class.
public class ResidentValidationController {
    //public  static ResidentDetailRequest resident;
@AuraEnabled(cacheable=true)
    public static ResidentDetailRequest getResidentFromOpportunity(String opptyId){
        Opportunity oppy = getOpportunityFromId(opptyId);
        ResidentDetailRequest residentTemp;
        if(oppy != null){
        
            residentTemp = new ResidentDetailRequest();
            residentTemp.FirstName = oppy.Patient_Name_pc__r.FirstName;
            residentTemp.LastName = oppy.Patient_Name_pc__r.LastName;
            residentTemp.DOB = String.valueOf(oppy.DOB__c);
            residentTemp.SSN = oppy.SSN_ShieldEncryption__c;
            residentTemp.FacilityName = oppy.Facility_Name__c;
            residentTemp.FacilityNumber = Integer.valueOf(oppy.Facility__r.Facility_Number__c);
            residentTemp.MedicalRecordNumber = oppy.MedicalRecordNumber__c;
            
        }

       
        return residentTemp;
    }
    
  private static Opportunity getOpportunityFromId(Id opptyId){
        return [SELECT Id, DOB__c,Patient_Name_pc__c, Facility_Name__c, Last_Validation__c,                             Facility__r.Facility_Number__c,
                   SSN_ShieldEncryption__c,MedicalRecordNumber__c,
                   Patient_Name_pc__r.FirstName,Patient_Name_pc__r.LastName
                  FROM Opportunity WHERE Id =: opptyId];
    }
}

// LWC component code.
import { LightningElement,api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getResident from 
'@salesforce/apex/ResidentValidationController.getResidentFromOpportunity';
@api recordId
connectedCallback() {
        console.log('this is oppy Id',this.recordId);
        if(this.recordId){
            getResident({opptyId:this.recordId})
             .then(res=>{
                this.resident = res;
                
                let missingFields = this.getMissingFields(res);
                console.log('field missed',missingFields);
                if(missingFields){
                    let msg = "Opportunity is missing some required fields ("+missingFields+")";
                    this.showError(msg);
                }
}).catch(err=>{
                    this.showError(err.body.message);
});
}
}
getMissingFields(resident){
        let missing = [];
 
        if(resident.FirstName == null || resident.FirstName.trim() == ''){
            missing.push("First Name");
        }
        if(resident.LastName == null || resident.LastName.trim() == ''){
            missing.push("Last Name");
        }
        if(resident.SSN == null || resident.SSN.trim() == ''){
            missing.push("SSN");
        }
        if(resident.DOB == null || resident.DOB.trim() == ''){
            missing.push("DOB");
        }

        console.log('missing fields', missing);
        if(missing.length > 0){
            return missing.join(', ');
        }else{
            return null;
        }
    }
showError(msg){
        const evt = new ShowToastEvent({
            title: 'Resident Validation Error',
            message: msg,
            variant: "error"
        });
        this.dispatchEvent(evt);
    }

The idea here is just to make one call to apex, get information and throw error
if any information missing combing.

Comments

saasguru said…
How to connect wwith you? Please drop a mail at akshay.nair@saasguru.co

Popular posts from this blog

Style in LWC

 Following are the ways we can apply in CSS in LWC. 1. Inline CCS Inline CSS is not recommended approaches, it is take highest priority among all CSS. style="color:green;font-size:10px;" is inline CSS added to div < template >     < lightning-card title = "Inline CSS" >         < div >             < div style = "color:green;font-size:10px;" > This is inline Style div </ div >         </ div >     </ lightning-card > </ template >  2. External CSS style can be applied to an elements such as h1, p,div span etc. It can applied to class using "." notation. for example .user{} It can also be applied to pseudo class.  for example .user:hover{} Id locator is not being used in LWC to apply style To apply external css, need to create separate CSS file, file name should be exactly matched with component name. for example - If component name is ...

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 ...

Lifecycle hooks in LWC

There are 3 phase of LWC component  1. Mounting  A. constructor, B. connnectedCallback C. render D. renderedCallback 2. UnMounting  A. disconnectedcallback 3. Error  A.errorcallback Note - render is not lifecycle hook, it is protected method of Lightning element class. Mounting Phase LWC Creation and Render Life cycle Constructor Method ·        This method called when component is instantiated and It flows from parent to child component. ·        Need to call Super() inside constructor method ·        Can’t access any component properties or child component because it’s not ready yet. ·        Host element can be accessed through “this. template” inside constructor method. ·        Don’t add any attributes to host inside constructor C   constructor (){          super (); //...