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

How to Create a Tooltip in Lightning Datatable ?

Imagine you have a datatable displaying a list of Contact records , and one of the columns shows the Account Name . The Account Name is a hyperlink that allows users to navigate to the Account record page. But what if users want to take a quick glance at some key Account fields —like Phone or Address—without navigating to the Account record? In Salesforce Classic, this was achieved using the Mini Page Layout feature from standard page. However, in Lightning Experience, we can implement a similar feature by adding a tooltip to the data table. Solution Overview: We’ll create a Lightning Web Component (LWC) that: Displays a data table with a clickable Account Name . Provides a tooltip that shows the Account's Phone and Address fields when users hover over the Account Name. Implementation Steps: 1. Data Preparation We need to retrieve the following fields for each Contact and its associated Account: Contact Fields : Name, Phone, Email Account Fields : Name, Phone, Billing Addre...

📆 How to Get the Start and End Date of the Previous Quarter in Apex ?

 When working with Salesforce data, it's often necessary to filter or report on records from a specific quarter . If you're looking to retrieve the start and end dates of the previous quarter based on the current date, here’s a simple and reusable Apex utility you can use. 🔧 Apex Utility Methods Below are two helper methods: getStartDate() — Calculates the start date of the previous quarter . getEndDate() — Calculates the end date of the previous quarter , based on the start date. // Helper method to get the start date of the previous quarter private Date getStartDate () {     Date today = Date . today ();     Integer currentYear = today . year ();     Integer currentMonth = today . month ();     // Determine the first month of the previous quarter     Integer previousQuarterStartMonth = (( currentMonth - 1 ) / 3 ) * 3 + 1 - 3 ;     // Adjust the year if the previous quarter falls in the previ...

Add/Remove Functionality in a VF page for Creating Multiple Records For a Particular Object.

Hi Guys This is a very simple post. I had come across a scenario where I was asked to develop some functionality where user can create list of records at a time(clicking on save button on one time) and can remove row. Here I have created a pageblock table and there I am displaying 5 rows to enter data and there column, Name , Phone and Action. In Action column Delete link is present.When that link(Delete) is clicked then particular row will be removed. Two button is there Add Row and Save. Add Row-->  When that button is clicked one more row will be created in the pagablock table Save--> It will save the record. Here is the page <apex:page controller="creatingListOfRecordsController">     <apex:form >              <apex:pageBlock title="Creating List Of Account Records">         <apex:pageMessages></apex:pageMessages>             ...