Skip to content
Home » Blog Archive » The Easy Guide to Mapping Salesforce Object Fields to Apex and LWC JavaScript Data Types

The Easy Guide to Mapping Salesforce Object Fields to Apex and LWC JavaScript Data Types

Working with data types is a big part of being a Salesforce developer. You’ll often have to use different data types when writing code in Apex or Lightning Web Components (LWC) JavaScript. It’s super important to map Salesforce object fields to the right data types in Apex and JavaScript. This way, you can be sure your data is accurate and your app runs smoothly. Even though you don’t always need to set data types for JavaScript variables, knowing what data types you’re working with can save you from headaches and help you write better code.

In this blog post, we’re going to give you a handy table that shows you how to map Salesforce object fields data types to Apex and JavaScript data types. This table is perfect for a quick check when you’re coding and helps you understand how different data types work together. We’ll also go through some examples to show you why it’s a good idea to know the data types in JavaScript, even if you don’t always have to set them.

If you’re new to Salesforce Apex or want to dive deeper into Apex data types, we recommend checking out our “Beginner’s Guide to Salesforce Apex: Primitive Data Types and Methods” blog post. This post will help you understand the basics of Apex primitive data types and their methods. And if you want to learn more about working with collections in Apex, such as lists, sets, and maps, take a look at our “Beginner’s Guide to Salesforce Apex: An Introduction to Collections – Lists, Sets, and Maps” blog post.

By the end of this post, you’ll be a pro at working with Salesforce data types in both Apex and JavaScript, and you’ll be able to build more efficient and reliable apps.

Comparing Salesforce Object Fields Data Types in Apex and LWC JavaScript

Salesforce Data TypeApex Data TypeJavaScript Data TypeNotes
1. Text
2. Text Area
StringString1. Data Type: Salesforce Object “Text” and “Text Area” fields are mapped to the Apex String data type and LWC JavaScript String data type.

2. Length Limit: Salesforce Object Text and Text Area fields have a max limit of 255 characters, while Apex and JavaScript can handle much larger strings. To avoid errors, always trim long text before assigning it to a Salesforce Object Text or Text Area field.
Text Area (Long)StringString1. Data Type: Salesforce Object “Text Area (Long)” fields are mapped to the Apex String data type and LWC JavaScript String data type.

2. Length Limit: Salesforce Object Long Text Area fields have a max limit of 131,072 characters, while Apex and JavaScript can handle much larger strings. To avoid errors, always trim long text before assigning it to a Salesforce Object Text Area (Long) field.
Text Area (Rich)StringString1. Data Type: Salesforce Object “Text Area (Rich)” fields are mapped to the Apex String data type and LWC JavaScript String data type.

2. Length Limit: Salesforce Object Rich Text Area fields have a max limit of 131,072 characters, while Apex and JavaScript can handle much larger strings. To avoid errors, always trim long text before assigning it to a Salesforce objectText Area (Rich) field.

3. Keep in mind that Rich Text Area fields also store HTML formatting, which counts towards the character limit.
EmailStringString1. Data Type: Salesforce Object “Email” fields are mapped to the Apex String data type and LWC JavaScript String data type.

2. Length Limit: Salesforce Object Email fields have a max limit of 80 characters, while Apex and JavaScript can handle much larger strings. To avoid errors, always trim long email addresses before assigning them to a Salesforce Object Email field.

3. Format Validation: If the format of the email address is incorrect in Apex or LWC JavaScript String fields, assigning it to a Salesforce Object Email field would cause an error. To avoid errors, always ensure that the email addresses are valid and properly formatted before assigning them to a Salesforce Object Email field.
1. Number
2. Currency
3. Percent
Decimal
Double
Number1. Data Type: Salesforce Object “Number”, “Currency”, and “Percentage” fields are mapped to the Apex Decimal or Double data type and LWC JavaScript Number data type.

2. Precision and Scale:
– Salesforce Object Number,Currency or Percent fields have limits on precision (total number of digits) and scale (number of digits after the decimal point).

– Apex Decimal and Double, and JavaScript Number can handle larger and more precise values.

– To avoid errors, ensure that the number values in Apex or JavaScript adhere to the precision and scale limits defined for the Salesforce Object Number,Currency or Percent field before assigning them.

– Choose between Decimal and Double in Apex depending on your specific requirements and the level of precision needed for your calculations.

3. Other Notes:
– Percent fields in Salesforce display the percentage symbol while Decimal data types in Apex do not display the percentage symbol.
DateDateDate 1.Data Type: Salesforce Object “Date” fields are mapped to the Apex Date data type and LWC JavaScript Date object.

2. Other Notes:
– Salesforce Object “Date” fields are stored in the format “YYYY-MM-DD” and can be displayed in different formats using Visualforce or Lightning components.

– In Apex and LWC JavaScript, the Date data type can be used to perform operations and calculations on dates.
DateTimeDateTimeDate1. Data Type: Salesforce Object “DateTime” fields are mapped to the Apex DateTime data type and LWC JavaScript Date object.

2. TimeZone:
– Date/Time fields in Salesforce store values in the UTC timezone.

– In Apex and LWC JavaScript, the date-time value is stored in the user’s time zone by default, but can be converted to UTC or a specific time zone using the Timezone class or the Intl.DateTimeFormat() method, respectively.

3. Other Notes:
– Format: Salesforce Object “DateTime” fields are stored in the format “YYYY-MM-DDTHH:MM:SS.SSSZ” and can be displayed in different formats using Visualforce or Lightning components.

– In Apex and LWC JavaScript, the DateTime data type can be used to perform operations and calculations on date-time values.
TimeTimeString1. Data Type: Salesforce Object “Time” fields are mapped to the Apex Time data type and LWC JavaScript String.

2. Time Zone: Salesforce Object “Time” fields do not store time zone information, and the value is considered to be in the user’s time zone by default in Apex and LWC JavaScript.

3. Other Notes:
– Format: Salesforce Object “Time” fields store the time value in the format “HH:MM:SS.SSSZ” where “HH” is the hour (0-23), “MM” is the minute (0-59), “SS” is the second (0-59), and “SSS” is the millisecond (000-999). “Z” at the end denotes Greenwich Mean Time (GMT).

– In Apex, the Time data type can be used to perform operations and calculations on time values. In LWC JavaScript, the String data type can be used to store and display time values.
CheckboxBooleanBooleanNullability: Salesforce Object “Checkbox” fields cannot have a null value just True or False values, while Apex Boolean and LWC JavaScript Boolean data types can have a null value.
PicklistStringString1. Data Type: Salesforce Object “Picklist” fields store a single value selected from a list of predefined options and are mapped to the String data type in both Apex and LWC JavaScript.

2. Length Limit: Salesforce Object “Picklist” fields have a maximum length of 255 characters, while Apex and LWC JavaScript String data types can handle much longer strings.

3. Nullability: Salesforce Object “Picklist” fields can have a null value so be careful to handle null values in Apex and LWC.
Multi-Select PicklistString with “;” that can be converted to
List<String>
String with “;” that can be converted to
Array<String>
1. Data Type: Salesforce Object “Multi-Select Picklist” fields store a list of values selected from a list of predefined options and are mapped to the List<String> data type in Apex and the Array<String> data type in LWC JavaScript.

2. Length Limit: Salesforce Object “Multi-Select Picklist” fields have a maximum length of 255 characters per selected value, while Apex and LWC JavaScript Array data types can handle much longer strings.

3. Nullability: Salesforce Object “Multi-Select Picklist” fields can have a null value so be careful to handle null values in Apex and LWC.
LookupIdString1. Data Type: Salesforce Object “Lookup” fields store a reference to a single record in another object and are mapped to the Id data type in Apex and the String (Id) data type in LWC JavaScript.

2. Nullability: Salesforce Object “Lookup” fields can have a null value so be careful to handle null values in Apex and LWC.
Master-DetailIdString1. Data Type: Salesforce Object “Master-Detail” fields store a reference to a parent record and are mapped to the Id data type in Apex and the String data type in LWC JavaScript.

2. Nullability: Salesforce Object “Master-Detail” fields cannot have a null value, while Apex Id data type and LWC JavaScript String data type can have a null value so be careful to handle that properly.
Formula (depends on the formula output)(e.g., Decimal)(e.g., Number)1. Data Type: Salesforce Object “Formula” fields depend on the output data type of the formula expression and can be mapped to various data types in Apex and LWC JavaScript.

2. Nullability: The formula output can be null if the formula expression evaluates to null or if any of the formula input fields are null so be careful to handle null values in Apex and LWC.
Roll-Up SummaryDecimal
Double
Integer
NumberData Type: Salesforce Object “Roll-Up Summary” fields are mapped to the Apex Decimal, Double or Integer data type depending on the roll-up operation and LWC JavaScript Number.
Auto NumberStringStringAuto Number Salesforce Object fields are automatically generated by Salesforce and their values can’t be modified.
GeolocationLocationObjectData Type: Salesforce Object “Geolocation” fields are mapped to the Apex Location data type and LWC JavaScript Object.
PhoneStringString1. Data Type: Salesforce Object “Phone” fields are mapped to the Apex String data type and LWC JavaScript String.

2. Length Limit: Salesforce Object “Phone” fields have a maximum limit of 40 characters. In Apex and LWC JavaScript, there is no specific limit on the length of a String variable, but it is important to ensure that the phone number is properly formatted and within the character limit to avoid errors.
This table allows you to quickly compare and understand the mapping between Salesforce object fields data types, Apex data types, and LWC JavaScript data types. It can be particularly helpful for developers working across different platforms and languages in the Salesforce ecosystem.

Why understanding how to map Salesforce object fields to JavaScript data types is important in LWC Development?

You must be wondering why do we care about how to map Salesforce Object fields to Javascript data types if in Javascript we don’t explicitly specify variables data types.

You’re correct. In JavaScript, including Lightning Web Components (LWC), you do not explicitly define the data type of a variable when declaring it. JavaScript is a dynamically-typed language, which means that data types are determined automatically during runtime.

The table provided earlier is to help you understand how Salesforce object fields data types would map to JavaScript data types when you use them in your LWC code. Although you don’t explicitly define the data types in your JavaScript code, it’s essential to be aware of the appropriate data types when manipulating or processing the data within your LWC.

For example, when working with a Date field in LWC, you would typically use JavaScript’s built-in Date object to handle date-related operations. Knowing the data types helps you work effectively with the data and avoid potential issues caused by using inappropriate data types or data type conversions.

Example mapping Salesforce DateTime field to LWC Javascript Date object

Let’s take an example of working with an Account object in Salesforce and displaying its Name (Text), CreatedDate (DateTime) fields in a Lightning Web Component. We will focus on the CreatedDate field and how we can utilize several Javascript method to process the DateTime field in different ways.

accountDetails.html

<!-- accountDetails.html -->
<template>
    <lightning-card title="Account Details">
        <div class="slds-box">
            <p><b>Name:</b> {accountName}</p>
            <p><b>Created Date as is: </b>{createdDate}</p>
            <p><b>Created Date Formated Date:</b> {formattedCreatedDate}</p>
            <p><b>Created Date Formatted Date String: </b>{formattedCreateDateString}</p>
            <p><b>Full Year Value:</b> {fullYearValue}</p>
            <p><b>Day Value [Sunday - Saturday : 0 - 6] : </b>{dayValue}</p>
            <p><b>Today Date: </b>{todayDate}</p>
            <p><b>Account was Created </b>{daysDifference}<b> days ago!!</b></p>
        </div>
    </lightning-card>
</template>
accountDetails.js

// accountDetails.js
import { LightningElement, wire, track } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

const ACCOUNT_FIELDS = ['Account.Name', 'Account.CreatedDate'];
const ACCOUNT_ID = '001XXXXXXXXXXXXXXX'; // Replace with a valid Account Id in Your Org

export default class AccountDetails extends LightningElement {
    @track accountName;
    @track createdDate;

    @wire(getRecord, { recordId: ACCOUNT_ID, fields: ACCOUNT_FIELDS })
    wiredAccount({ error, data }) {
        if (data) {
            this.accountName = data.fields.Name.value;
            
            //Javascript constructor for Date object
            this.createdDate = new Date(data.fields.CreatedDate.value);
        } else if (error) {console.error('Error fetching account data:', error);}
    }

    get formattedCreatedDate() {
      //Javascript method toLocaleDateString used to get the Date Only String 
      //in user Locale
      return this.createdDate ? this.createdDate.toLocaleDateString() : '';
    }
    
    get formattedCreateDateString(){
        //Javascript method toLocaleString used to get the Date and time String 
        //in user Locale
        return this.createdDate? this.createdDate.toLocaleString():'';
    }
    
    get fullYearValue(){
       //Javascript method getFullYear used to get the year value
       return this.createdDate?this.createdDate.getFullYear():'';
    }
    
    get dayValue(){
       //Javascript method getDay used to get the day index of the week
       return this.createdDate?this.createdDate.getDay():'';
    }
    
    get todayDate(){
       return new Date().toLocaleDateString();
    }

    //Used to get the number of days difference between today's date and the created
    //date value of the account
    get daysDifference(){
        if(this.createdDate){
            const today = new Date();
            const diffTime = Math.abs(today - this.createdDate);
            const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
            return diffDays;
        }
        return '';        
    }
}
accountDetails.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>57.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

The output when this component is added to the Account Lightning record page would look like:

Screenshot of an LWC component on the Account record page showing a date time field displayed using different JavaScript methods.
  • Created Date as is: This is using the merge field “{createdDate}”. This is how we are setting createdDate value using the new Date() javascript constructor and passing to it the Salesforce CreateDate field, if you pass a wrong field to the method, it will throw an exception
@wire(getRecord, { recordId: ACCOUNT_ID, fields: ACCOUNT_FIELDS })
    wiredAccount({ error, data }) {
        if (data) {
            this.accountName = data.fields.Name.value;
            this.createdDate = new Date(data.fields.CreatedDate.value);
        } else if (error) {console.error('Error fetching account data:', error);}
    }
  • Created Date Formatted: this is using the merge field “{formattedCreatedDate}”. The below code demonstrate how we used the javascript method “toLocaleDateString()” to get the Date String in user local format
 get formattedCreatedDate() {
        return this.createdDate ? this.createdDate.toLocaleDateString() : '';
  }

More examples to illustrate the benefits of knowing the data types in LWC

Number (Currency) Example

Let’s assume you want to display the revenue of an opportunity in a formatted currency string. Knowing that the ‘Amount’ field in the Opportunity object is a Currency data type, which maps to a JavaScript Number, will allow you to use the Intl.NumberFormat object to format the value correctly.

// Assuming you have fetched the 'Amount' value from Salesforce and stored it in a variable
const opportunityAmount = 12345.67;

// Format the opportunityAmount as a currency string
const formattedAmount = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(opportunityAmount);

console.log(formattedAmount); // Output: $12,345.67

Multi-Select Picklist Example

Let’s assume you have a custom object with a Multi-Select Picklist field called ‘Interests__c’. Knowing that this field maps to a JavaScript Array of Strings, you can easily manipulate and process the values in your LWC.

// Assuming you have fetched the 'Interests__c' value from Salesforce and stored it in a variable
const interestsString = 'Reading;Cooking;Hiking;Coding';

// Convert the Multi-Select Picklist string value to an array of strings
const interestsArray = interestsString.split(';');

// Process the interestsArray in your LWC, e.g., displaying the values as a list
//interestsArray ==> ['Reading', 'Cooking', 'Hiking', 'Coding']

Picklist Example

Suppose you have a custom object with a Picklist field called ‘Priority__c’. Knowing that this field maps to a JavaScript String, you can easily compare and process the values in your LWC.

// Assuming you have fetched the 'Priority__c' value from Salesforce and stored it in a variable
const priority = 'High';

// Perform a comparison to take action based on the priority value
if (priority === 'High') {
    // Execute code for high priority cases
} else if (priority === 'Medium') {
    // Execute code for medium priority cases
} else {
    // Execute code for low priority cases
}

Checkbox Example

Let’s assume you have a custom object with a Checkbox field called ‘IsActive__c’. Knowing that this field maps to a JavaScript Boolean, you can easily use it in conditional statements in your LWC.

// Assuming you have fetched the 'IsActive__c' value from Salesforce and stored it in a variable
const isActive = true;

// Use the value in a conditional statement
if (isActive) {
    // Execute code when the record is Active
} else {
    // Execute code when the record is not Active
}

Conclusion

Handling data types effectively is essential for any Salesforce developer working with Apex or Lightning Web Components (LWC) JavaScript. In this blog post, we provided a helpful table for mapping Salesforce object fields data types to their corresponding Apex and JavaScript data types. This table serves as a quick reference and ensures that you can work with different data types confidently and accurately across both platforms.

We also discussed examples that demonstrate the importance of understanding the underlying data types in JavaScript, even when you don’t explicitly define them. By following the guidance provided in this post, you’ll be better equipped to build efficient and reliable Salesforce applications.

With this foundation, you can continue to grow your Salesforce development skills and create increasingly powerful and efficient applications. Happy coding!

Resources

  1. Custom Fields: Quick Look
  2. Customize a Salesforce Object
  3. Custom Field Types
  4. Data Modeling
  5. Build Lightning Web Components
  6. Javascript : Intl.NumberFormat
  7. Javascript: Date Object and Methods
  8. Rounding and truncating numbers in JavaScript

Join the conversation

Your email address will not be published. Required fields are marked *