Close Menu
SalesforceCodex
    Facebook X (Twitter) Instagram
    Trending
    • How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI
    • Top Mistakes Developers Make in Salesforce Apex Triggers
    • Introducing Agentforce3 to Salesforce Developers
    • The Ultimate Guide to Apex Order of Execution for Developers
    • How to Handle Bulkification in Apex with Real-World Use Cases
    • How to Confidently Manage Transactions in Salesforce Apex
    • Building a Dynamic Tree Grid in Lightning Web Component
    • 10 Salesforce Chrome Extensions to Boost Your Productivity
    Facebook X (Twitter) Instagram
    SalesforceCodex
    Subscribe
    Tuesday, July 29
    • Home
    • Salesforce Platform
      • Architecture
      • Apex
      • Lightning Web Components
      • Integration
      • Flows & Automation
      • Best Practices
      • Questions
      • News
      • Books Testimonial
    • Industries
      • Artificial Intelligence
    • Hire Me
    • Certification
      • How to Prepare for Salesforce Integration Architect Exam
      • Certification Coupons
    • Downloads
      • Salesforce Release Notes
      • Apex Coding Guidelines
    • About Us
      • Privacy Policy
    • Contact Us
    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 Sahni6 Mins Read

    How to Leverage Model Context Protocol (MCP) to Enhance Salesforce AI

    July 28, 2025
    By Dhanik Lal Sahni7 Mins Read

    Top Mistakes Developers Make in Salesforce Apex Triggers

    July 25, 2025
    By Dhanik Lal Sahni14 Mins Read

    The Ultimate Guide to Apex Order of Execution for Developers

    July 20, 2025
    Add A Comment
    Leave A Reply Cancel Reply

    Ranked #1 Salesforce Developer Blog by SalesforceBen.com
    SFBenTopDeveloper
    Ranked #4 Salesforce Developer Blog by ApexHours.com
    ApexHoursTopDevelopers
    Categories
    Archives
    Tags
    apex (116) apex best practices (5) apex code best practice (10) apex code optimization (6) Apex logging (4) apex rest (11) apex trigger best practices (6) architecture (22) Asynchronous apex (9) AWS (5) batch apex (10) best code practice (4) code optimization (9) custom metadata types (5) design principle (9) flow (16) 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) optimize apex (5) optimize apex code (6) optimize apex trigger (5) Permission set (4) Queueable (9) queueable apex (4) rest api (23) salesforce (149) salesforce apex (52) salesforce api (4) salesforce api integration (5) Salesforce Interview Question (5) salesforce news (5) salesforce question (5) solid (6) tooling api (5) 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

    MailChimp

    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.