Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • Building a Dynamic Tree Grid in Lightning Web Component
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    • How to Implement Dynamic Queueable Chaining in Salesforce Apex
    • How to Implement Basic Queueable Chaining in Salesforce Apex
    • How to Suppress PMD Warnings in Salesforce Apex
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Saturday, July 5
    • Home
    • Architecture
    • Salesforce
      • News
      • Apex
      • Integration
      • Books Testimonial
    • Questions
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Integration Posts
    • Downloads
    • About Us
      • Privacy Policy
    SalesforceCodex
    Home»Salesforce»Apex»Sending Wrapper object to Apex from LWC

    Sending Wrapper object to Apex from LWC

    Dhanik Lal SahniBy Dhanik Lal SahniDecember 29, 2021Updated:June 11, 2023No Comments3 Mins Read
    Facebook Twitter Pinterest LinkedIn Tumblr Email
    Sending Wrapper Object to Apex | Pass custom object to Apex
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Most of the time we need to use the existing apex method which accepts custom wrapper objects as a parameter. This post will help in sending wrapper object to apex from LWC.

    There are two ways to pass the custom type or complex data to apex from LWC.

    1. Sending Wrapper object to Apex

    We can directly pass wrapper object to apex without any serialization and deserialization process. Let us take an example we have below wrapper class or DTO class in the apex

    public class AccountWrapper
    {
        @auraenabled
        public string Name{get;set;}
        @auraenabled
        public integer NumberOfEmployees{get;set;}
        @AuraEnabled
        public List<Contact> Contacts { get; set; }
    }

    This wrapper object is used in apex class to get data from LWC to insert Account and Contact objects. Use cases can be different for your project where you need to get complex data from LWC.

    public class AccountService {
        @auraenabled
        public static void createAccountContact(AccountWrapper wrapper)
        {
            system.debug('wrapper:'+wrapper);
            if(wrapper!=null)
            {
                Account act=new Account();
                act.Name=wrapper.Name;
                act.NumberOfEmployees=wrapper.NumberOfEmployees;
                insert act;
                
                if(wrapper.Contacts!=null)
                {
                    for(Contact ct:wrapper.Contacts)
                    {
                        ct.AccountId=act.id;
                    }
                    insert wrapper.Contacts;
                }
            }
        }
    }

    To pass this AccountWrapper wrapper object to apex we have to pass JSON data in method parameter in LWC. This is similar to the normal parameter passed to apex. Before we call any apex method we have to reference that method using import in LWC. So according to your method change it in LWC code.

    import { LightningElement } from 'lwc';
    import createAccountContact from '@salesforce/apex/AccountService.createAccountContact';
    export default class ApexWrapperCall extends LightningElement {
        contacts=[];
        error;
    
        handleClick(e)
        {
            var contact=
            {
                LastName:'Sahni',
                Email:'salesforcecodex@gmail.com',
                Phone:'9871506648'
            };
            this.contacts.push(contact);
            var pass=
            {
                Name:'Dhanik',
                NumberOfEmployees:2,
                Contacts:this.contacts
            };
            createAccountContact({wrapper:pass})
            .then(result => {
                console.log('Data:'+ JSON.stringify(result));
            }) .catch(error => {
                console.log(error);
                this.error = error;
            }); 
        }
    }

    Here is the output of apex where complete data is passed to apex.

    Send Wrapper object to Apex, Send Custom object to apex

    2. Send serialized string to Apex and deserialize it

    Passing wrapper to Apex using the first approach will work in the most scenario but if it is not working then pass wrapper data using serialized string. This serialized string will be deserialized as a wrapper object (Apex object) in the Apex class.

    JSON.deserialize method will be used to deserialize string into wrapper object.

    AccountWrapper wrapper=(AccountWrapper)JSON.deserialize(wrapperText,AccountWrapper.class);

    Apex Code:

    We expect data in this method as a string. After getting the string we are converting the string in the AccountWrapper object.

    public class AccountService {
        
        public class AccountWrapper
        {
            @auraenabled
            public string Name{get;set;}
            @auraenabled
            public integer NumberOfEmployees{get;set;}
            @AuraEnabled
            public List<Contact> Contacts { get; set; }
        }
        @auraenabled
        public static void createAccountContacts(string wrapperText)
        {
            system.debug('wrapperText:'+wrapperText);
            AccountWrapper wrapper=(AccountWrapper)JSON.deserialize(wrapperText,AccountWrapper.class);
            system.debug('wrapper:'+wrapper);
            if(wrapper!=null)
            {
                Account act=new Account();
                act.Name=wrapper.Name;
                act.NumberOfEmployees=wrapper.NumberOfEmployees;
                insert act;
                
                if(wrapper.Contacts!=null)
                {
                    for(Contact ct:wrapper.Contacts)
                    {
                        ct.AccountId=act.id;
                    }
                    insert wrapper.Contacts;
                }
            }
        }
    }

    LWC Code to pass wrapper object as a string:

    In LWC we have to create JSON objects like account variable in the below code. After creating JSON object convert it into a string to pass the apex.

    import { LightningElement } from 'lwc';
    import createAccountContacts from '@salesforce/apex/AccountService.createAccountContacts';
    export default class ApexWrapperCall extends LightningElement {
        contacts=[];
        error;
    
        handleClick(e)
        {
            var contact=
            {
                LastName:'Sahni',
                Email:'salesforcecodex@gmail.com',
                Phone:'9871506648'
            };
            this.contacts.push(contact);
            var account=
            {
                Name:'Dhanik Sahni',
                NumberOfEmployees:2,
                Contacts:this.contacts
            };
            createAccountContacts({wrapperText:JSON.stringify(account)})
            .then(result => {
                console.log('Data:'+ JSON.stringify(result));
            }) .catch(error => {
                console.log(error);
                this.error = error;
            }); 
        }
    }

    This will give output like the below image

    Send Custom object to Apex, Send Wrapper to Apex

    References:

    Stack Exchange

    Stop Serialization and Deserialization of Object In Apex

    Handle Heap Size for Apex Code Optimization

    Data Transformation with DataWeave in Salesforce Apex

    Secure Apex Code with User Mode Operation

    Object Initializer in Salesforce Apex

    Enhance Apex Performance with Platform Caching

    apex custom wrapper deserialization salesforce salesforce apex serialization wrapper
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleOptimizing Loop in Apex Code
    Next Article Optimize Code by Disabling Debug Mode
    Dhanik Lal Sahni
    • Website
    • Facebook
    • X (Twitter)

    With over 18 years of experience in web-based application development, I specialize in Salesforce technology and its ecosystem. My journey has equipped me with expertise in a diverse range of technologies including .NET, .NET Core, MS Dynamics CRM, Azure, Oracle, and SQL Server. I am dedicated to staying at the forefront of technological advancements and continuously researching new developments in the Salesforce realm. My focus remains on leveraging technology to create innovative solutions that drive business success.

    Related Posts

    By Dhanik Lal Sahni4 Mins Read

    Building a Dynamic Tree Grid in Lightning Web Component

    June 29, 2025
    By Dhanik Lal Sahni9 Mins Read

    10 Salesforce Chrome Extensions to Boost Your Productivity

    June 1, 2025
    By Dhanik Lal Sahni4 Mins Read

    How to Build a Generic Modal Window in Lightning Web Component

    May 26, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 SALESFORCE DEVELOPER BLOG BY SALESFORCEBEN.COM
    Featured on Top Salesforce Developer Blog By ApexHours
    Recent Posts
    • Building a Dynamic Tree Grid in Lightning Web Component
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    • How to Build a Generic Modal Window in Lightning Web Component
    • Top 10 Salesforce Flow Features of Salesforce Summer ’25
    • Unlock the Power of Vibe Coding in Salesforce
    Ranked in Top Salesforce Blog by feedspot.com
    RSS Recent Stories
    • Top 20 Salesforce Data Cloud Interview Questions & Answers for Admins June 5, 2025
    • How to Connect Excel to Salesforce to Manage Your Data and Metadata February 9, 2025
    • Difference Between With Security and Without Security in Apex January 2, 2025
    • Top Reasons to Love Salesforce Trailhead: A Comprehensive Guide December 5, 2024
    • How to Utilize Apex Properties in Salesforce November 3, 2024
    Archives
    Categories
    Tags
    apex (112) apex code best practice (8) apex rest (11) apex trigger best practices (4) architecture (22) Asynchronous apex (9) AWS (5) batch apex (9) batch processing (4) code optimization (8) custom metadata types (5) design principle (9) einstein (3) flow (15) future method (4) google (6) google api (4) integration (19) integration architecture (6) lighting (8) lightning (66) lightning-combobox (5) lightning-datatable (10) lightning component (32) Lightning web component (64) lwc (53) named credential (8) news (4) optimize apex code (4) Permission set (4) Queueable (9) rest api (23) S3 Server (4) salesforce (143) salesforce apex (48) salesforce api (4) salesforce api integration (5) salesforce bulk api (3) Salesforce Interview Question (4) salesforce news (5) salesforce question (5) solid (6) tooling api (5) Visual Studio Code (3) Winter 20 (8)

    Get our newsletter

    Want the latest from our blog straight to your inbox? Chucks us your detail and get mail when new post is published.
    * indicates required

    Facebook X (Twitter) Instagram Pinterest YouTube Tumblr LinkedIn Reddit Telegram
    © 2025 SalesforceCodex.com. Designed by Vagmine Cloud Solution.

    Type above and press Enter to search. Press Esc to cancel.

    Ad Blocker Enabled!
    Ad Blocker Enabled!
    Our website is made possible by displaying online advertisements to our visitors. Please support us by disabling your Ad Blocker.