Salesforce-Platform-Developer-II Practice Test Questions

202 Questions


Consider the following code snippet:

The Apex method is executed in an environment with a large data volume count for Accounts, and the query is performing poorly.
Which technique should the developer implement to ensure the query performs optimally, while preserving the entire result set?


A. Create a formula field to combine the createdDate and RecordType value, then filter based on the formula.


B. Break down the query into two individual queries and join the two result sets.


C. Annotate the method with the @Future annotation


D. Use the Database queryLocator method to retrieve the accounts.





D.
  Use the Database queryLocator method to retrieve the accounts.

Explanation:

The Apex method getAccounts queries Accounts based on CreatedDate or RecordTypeId, operating in an environment with a large data volume where the query performs poorly. To optimize performance while preserving the entire result set, the solution must address query efficiency, potentially leveraging batch processing or indexing, without altering the logical outcome. The technique should align with Salesforce best practices for handling large datasets and respect governor limits.

Correct Answer: D. Use the Database.queryLocator method to retrieve the accounts
Option D is the correct technique. The Database.queryLocator method, used with Database.Batchable or Database.getQueryLocator(), is designed for processing large datasets by enabling batch execution. It retrieves records in chunks (up to 50 million records), optimizing query performance by avoiding heap size limits and reducing the load on the system. This preserves the entire result set (Accounts where CreatedDate = thisDate or RecordTypeId = goldenRT) while improving efficiency in a high-volume environment. This approach is ideal for the Platform Developer II exam, focusing on scalable query handling.

Incorrect Answer:

Option A: Create a formula field to combine the createdDate and RecordType value, then filter based on the formula
Option A suggests creating a formula field to combine CreatedDate and RecordTypeId for filtering. While a formula could concatenate these values, it would not inherently improve query performance, as the underlying SOQL still scans the same large dataset. Formula fields are not indexed by default, and this approach adds maintenance overhead without addressing the root performance issue. It also risks complicating the logic and does not guarantee preservation of the full result set, making it suboptimal.

Option B: Break down the query into two individual queries and join the two result sets
Option B proposes splitting the query into two (e.g., one for CreatedDate and one for RecordTypeId) and joining the results. However, Apex does not support joining query results directly, and this would require manual list manipulation, increasing code complexity and memory usage. This approach does not inherently optimize the query against a large dataset and could exceed governor limits (e.g., 10,000 DML rows) if not batched, failing to address the performance issue effectively.

Option C: Annotate the method with the @Future annotation
Option C suggests using the @Future annotation to run the method asynchronously. While this moves the execution to a separate thread, avoiding immediate governor limit conflicts, it does not optimize the query itself. The same poorly performing SOQL would still execute, potentially hitting heap size or CPU time limits in the future context. It also does not handle large result sets efficiently without batching, making it an incomplete solution for preserving the entire result set while improving performance.

Reference:
Salesforce Apex Developer Guide: "Database.QueryLocator".
Salesforce Governor Limits

A company has a native iOS order placement app that needs to connect to Salesforce to retrieve consolidated information from many different objects in a JSON format. Which is the optimal method to implement this in Salesforce?


A. Apex REST web service


B. Apex SOAP web service


C. Apex SOAP callout


D. Apex REST callout





A.
  Apex REST web service

Explanation:

When a native iOS app needs to connect to Salesforce and retrieve data from multiple objects in JSON format, the best approach is to expose an Apex REST web service.

Why Apex REST is optimal:

✅ JSON-native: REST APIs natively return data in JSON, which is ideal for mobile platforms like iOS that handle JSON easily.
✅ Customizable Response: Apex REST methods allow you to query multiple objects, consolidate data, and return a custom JSON structure, all in one response — perfect for mobile app consumption.
✅ Stateless & Lightweight: REST APIs are lightweight and stateless, which makes them ideal for mobile devices with limited bandwidth and resources.
✅ OAuth-Compatible: REST services in Salesforce work seamlessly with OAuth 2.0, allowing secure access from external mobile apps.

❌ Incorrect Answers:

B) Apex SOAP web service
While Apex SOAP web services can expose Salesforce data, SOAP is XML-based, which is heavier and less mobile-friendly than JSON. iOS apps typically use JSON over REST for better performance and easier parsing. SOAP also requires WSDLs and extra configuration, which introduces unnecessary complexity for mobile integration.

C) Apex SOAP callout
This refers to Salesforce making a SOAP call to an external system, not receiving a call from an iOS app. This doesn’t apply to the question — the iOS app is the client, and Salesforce is the provider. So this direction of integration is incorrect.

D) Apex REST callout
Again, a REST callout is when Salesforce calls out to another external system via HTTP REST. In this scenario, Salesforce is not initiating the call — the iOS app is. So, REST callout is irrelevant here.

🔗 Reference:
Salesforce Developer Guide – Apex REST
Trailhead – Expose Data with Apex REST
Mobile SDK Guide – iOS to Salesforce

A developer needs to implement a system audit feature that allows users, assigned to a custom profile named "Auditors", to perform searches against the historical records in the Account object. The developer must ensure the search is able to return history records that are between 6 and 12 months old.
Given the code below, which select statement should be inserted below as a valid way to retrieve the Account History records ranging from 6 to 12 months old?


A. Option A


B. Option B


C. Option C


D. Option D





C.
  Option C

Explanation:

The developer needs to implement a system audit feature to allow users with the "Auditors" profile to search Account history records between 6 and 12 months old. The code snippet defines variables initialDate and endDate using System.today().addMonths(-12) and System.today().addMonths(-6), respectively, representing the date range. The SELECT statement must query the AccountHistory object, which tracks field changes, and filter records where CreatedDate falls within this range (initialDate to endDate). The solution should ensure accurate date filtering and align with Salesforce SOQL syntax.

Correct Answer: Option C
Option C is the correct SELECT statement. It queries AccountId, CreatedDate, Field, NewValue, and OldValue from the AccountHistory object, which stores historical changes to Account fields. The WHERE clause uses CreatedDate >= :initialDate AND CreatedDate <= :endDate to filter records between 6 and 12 months old, leveraging the bind variables initialDate (12 months ago) and endDate (6 months ago) defined earlier. This ensures the query returns the exact range required, adhering to SOQL best practices and supporting the audit feature for the "Auditors" profile.

Incorrect Answer:

Option A:
Option A uses CreatedDate >= :initialDate AND CreatedDate < :endDate, which includes records from 12 months ago up to, but not including, 6 months ago. This excludes records exactly at the endDate (6 months ago), potentially missing relevant history data. For an inclusive range of 6 to 12 months, the query should use <= :endDate to capture all records up to and including 6 months ago. This subtle exclusion makes Option A incorrect for the full requirement.

Option B:
Option B reverses the date range with CreatedDate >= :endDate AND CreatedDate < :initialDate, which would filter records from 6 months ago to before 12 months ago. This inverts the intended range (6 to 12 months old), returning an empty or incorrect result set since endDate (6 months ago) is greater than initialDate (12 months ago). This logical error fails to meet the requirement of retrieving history records between 6 and 12 months old.

Option D:
Option D uses CreatedDate >= :initialDate AND CreatedDate > :endDate, which attempts to filter records from 12 months ago where CreatedDate is also after 6 months ago. This creates a contradictory condition, as no date can be both >= 12 months ago and > 6 months ago, resulting in an empty result set. The incorrect use of > instead of <= for endDate invalidates the query, making it unsuitable for the 6 to 12-month range requirement.

Reference:
Salesforce Object Query Language (SOQL)
Salesforce Data Model: "AccountHistory Object".

An org records customer order information in a custom object, ordar__c, that has fields for the shipping address. A developer is tasked with adding code to calculate shipping charges on an order, based on a flat percentage rate associated with the region of the shipping address. What should the developer use to store the rates by region, so that when the changes are deployed to production no additional steps are needed for the calculation to work?


A. Custom hierarchy setting


B. Custom metadata type


C. Custom list setting


D. Custom object





B.
  Custom metadata type

Explanation:

The most appropriate choice is Custom Metadata Type, because it allows you to store configuration data, like shipping rates by region, in metadata, and it is:

✅ Deployed with change sets, unlocked packages, or metadata API — no post-deployment steps like data entry required.
✅ Accessible in Apex without querying (like CustomMetadataType__mdt.getAll()), which improves performance.
✅ Non-editable by end users in production without permission (unlike Custom Settings), ensuring stability.
✅ Ideal for application configuration values like shipping percentages, tax rates, thresholds, etc.

In this use case:
You’d create a Custom Metadata Type like Shipping_Rate__mdt
It would have fields like Region__c and Rate__c
You could query or access it in Apex to calculate charges

Example Apex usage:
Map rates = Shipping_Rate__mdt.getAll();
Decimal rate = rates.get(order.Region__c).Rate__c;
order.Shipping_Charge__c = order.Amount__c * rate;

This ensures that shipping logic works immediately after deployment, with no manual steps required in the production org.

❌ Incorrect Answers:

A) Custom hierarchy setting
Hierarchy settings are meant for user- or profile-specific configuration — not for general data like region-based shipping rates. They support per-user overrides, which is unnecessary and confusing for a flat shipping percentage by region. Also, their data must be manually created or updated in production after deployment unless you use a script.

C) Custom list setting
Custom list settings are similar to custom objects but are data, not metadata, meaning they require post-deployment data population. You cannot deploy data in list settings via metadata tools alone — you’d need to run a script or manually enter the data in production, violating the requirement.

D) Custom object
Custom objects are used to store business data, not configuration. Like list settings, the data in custom objects must be manually populated or scripted post-deployment, which contradicts the requirement that the calculation works immediately after deployment. This introduces operational overhead and risk.

🔗 Reference:
Salesforce – Custom Metadata Types Overview
Trailhead – Configure Your App Using Custom Metadata Types

A company uses an external system to manage its custom account territory assignments. Every quarter, millions of Accounts may be updated in Salesforce with new Owners when the territory assignments are completed in the external system. What is the optimal way to update the Accounts from the external system?


A. SOAP API


B. Apex REST Web Service


C. Composite REST API


D. Bulk ApI





D.
  Bulk ApI

Explanation:

The company updates millions of Accounts quarterly with new Owners based on territory assignments from an external system. The solution must handle large data volumes efficiently, minimize governor limit issues, and ensure scalability. The method should support bulk data processing and integrate seamlessly with Salesforce.

Correct Answer: D. Bulk API
Option D, Bulk API, is the optimal choice for updating millions of Accounts. It is designed for processing large data volumes asynchronously, allowing batch uploads of up to 10,000 records per batch and handling up to 200 million records per 24 hours. This minimizes governor limit constraints, supports CSV or XML data from the external system, and efficiently updates OwnerId fields. For the Platform Developer II exam, this demonstrates understanding of high-volume data integration, outperforming SOAP API, Apex REST, or Composite REST due to its scalability.

Incorrect Answers:

A. SOAP API: Limited to 200 records per call, it’s inefficient for millions of records, risking governor limits.

B. Apex REST Web Service: Requires custom Apex, limiting scalability and adding maintenance overhead for bulk updates.

C. Composite REST API: Handles multiple requests in one call but is capped at 25 sub-requests, unsuitable for millions of records.

Reference:
Salesforce Bulk API 2.0 and Bulk API

Consider the queries in the options below and the following Information:

* For these queries, assume that there are more than 200,000 Account records.
* These records Include soft-deleted records; that is, deleted records that are still in the Recycle Bin.
* There are two fields that are marked as External Id on the Account. These fields are customer_Number_c and ERR_Key_ s.

Which two queries are optimized for large data volumes?
(Choose 2 answers)


A. SELECT Id FROM Account WHERE Name !— NULL


B. SELECT 1d FROM Accounts WHERE Name != '° AND Customer_Number_c- "ValueA’


C. SELECT ID FROM Account WHRE id IN :aListVariable


D. SELECT Id FROM Account WHERE Name != ‘ ‘AND IsDeleted = false





B.
  SELECT 1d FROM Accounts WHERE Name != '° AND Customer_Number_c- "ValueA’

D.
  SELECT Id FROM Account WHERE Name != ‘ ‘AND IsDeleted = false

Explanation:

With over 200,000 Account records, including soft-deleted ones, and two external ID fields (Customer_Number__c, ERP_Key__s), the queries must be optimized for large data volumes. Optimization involves using indexed fields (e.g., external IDs), avoiding full table scans, and excluding soft-deleted records unless required. Salesforce recommends leveraging indexes and selective filters.

Correct Answers:
B. SELECT Id FROM Account WHERE Name != '' AND Customer_Number__c = 'ValueA'
D. SELECT Id FROM Account WHERE Name != '' AND IsDeleted = false

B: Option B is optimized because it filters on Customer_Number__c, an external ID field, which is indexed, enabling efficient record retrieval even with 200,000+ records. The Name != '' condition ensures non-null names, further refining the query. External ID indexes reduce scan time, making this suitable for large data volumes. This aligns with Salesforce best practices for selective queries, a key focus for the Platform Developer II exam.

D: Option D is optimized by including IsDeleted = false, which excludes soft-deleted records from the Recycle Bin, reducing the dataset size. The Name != '' filter adds selectivity, though it’s not indexed. This query avoids full table scans on all 200,000+ records, improving performance. For large volumes, excluding deleted records is a standard optimization technique, making this a valid choice.

Incorrect Answers:

A. SELECT Id FROM Account WHERE Name != NULL: Lacks an indexed field and scans all records, performing poorly with large data.

C. SELECT Id FROM Account WHERE Id IN :aListVariable: Depends on aListVariable size; with many IDs, it can hit governor limits and lacks index optimization.

Reference:
Salesforce SOQL SELECT Syntax

A developer is writing code that requires making callouts to an external web service. Which scenario necessitates that the callout be made in an asynchronous method?


A. The callouts will be made in an Apex trigger.


B. The callouts will be made using the REST APL.


C. Over 10 callouts will be made in a single transaction.


D. The callout could take longer than 60 seconds to complete.





D.
  The callout could take longer than 60 seconds to complete.

Explanation:

Callouts to external web services in Apex must comply with governor limits (e.g., 100 callouts per transaction, 120-second timeout). Asynchronous methods bypass some synchronous constraints, ensuring reliability for specific scenarios. The question identifies when this is necessary.

Correct Answer: D. The callout could take longer than 60 seconds to complete
Option D is correct because Salesforce imposes a 60-second timeout limit for synchronous callouts. If a callout exceeds this (e.g., due to slow external service response), it fails unless executed asynchronously using @Future, Queueable, or Batch Apex. Asynchronous methods extend the timeout to 120 seconds, ensuring completion. This is critical for the Platform Developer II exam, highlighting governor limit awareness and callout optimization.

Incorrect Answers:

A. The callouts will be made in an Apex trigger: Triggers support synchronous callouts (up to 100), so asynchronous isn’t required.

B. The callouts will be made using the REST API: REST API usage doesn’t mandate asynchronous execution.

C. Over 10 callouts will be made in a single transaction: The limit is 100, so 10 callouts are permissible synchronously.

Reference:
Salesforce Execution Governors and Limits

Universal Containers uses Big Objects to store almost a billion customer transactions called Customer_Transaction__b.
These are the fields on Customer_Transaction__b:
Account__c -
Program__c -
Points_Earned__c -
Location__c -
Transaction_Date__c -
The following fields have been identified as Index Fields for the Customer_Transaction__b object: Account__c, Program__c, and Transaction_Date__c.
Which SOQL query is valid on the Customer_Transaction__b Big Object?


A. SELECT Account__c, Program__c, Transaction_Date__c FROM Customer_Transaction__b WHERE Account__c = '001R000000302D3' AND Program__c ='Shoppers' AND Transaction_Date__c=2019-05-31T00:00Z


B. SELECT Account__c, Program__c, Transaction_Date__c FROM Customer_Transaction__b WHERE Account__c = '001R000000302D3' AND Program__c LIKE 'Shop%' AND Transaction_Date__c=2019-05-31T00:00Z


C. SELECT Account__c, Program__c, Transaction_Date__c FROM Customer_Transaction__b WHERE Account__c = '001R000000302D3' AND Program__c INCLUDES ('Shoppers', 'Womens') AND Transaction_Date__c=2019-05-31T00:00Z


D. SELECT Account__c, Program__c, Transaction_Date__c FROM Customer_Transaction__b WHERE Account__c = '001R000000302D3' AND Program__c EXCLUDES ('Shoppers', 'Womens') AND Transaction_Date__c=2019-05-31T00:00Z





A.
  SELECT Account__c, Program__c, Transaction_Date__c FROM Customer_Transaction__b WHERE Account__c = '001R000000302D3' AND Program__c ='Shoppers' AND Transaction_Date__c=2019-05-31T00:00Z

Explanation:

The Customer_Transaction__b Big Object has indexed fields (Account__c, Program__c, Transaction_Date__c). Big Object SOQL supports only SELECT, WHERE with indexed field equality or range filters, and LIMIT. Other operators (e.g., LIKE, INCLUDES, EXCLUDES) or non-indexed filters are invalid.

Correct Answer: A. SELECT Account__c, Program__c, Transaction_Date__c FROM Customer_Transaction__b WHERE Account__c = '001R000000302D3' AND Program__c = 'Shoppers' AND Transaction_Date__c = 2019-05-31T00:00Z
Option A is valid because it uses equality operators (=) on all indexed fields (Account__c, Program__c, Transaction_Date__c), which Big Objects support for efficient querying. The query retrieves specific transaction data for a given account, program, and date, leveraging the indexes to filter nearly a billion records. This adheres to Big Object SOQL restrictions, making it a correct choice for the Platform Developer II exam.

Incorrect Answers:

B. SELECT Account__c, Program__c, Transaction_Date__c FROM Customer_Transaction__b WHERE Account__c = '001R000000302D3' AND Program__c LIKE 'Shop%' AND Transaction_Date__c = 2019-05-31T00:00Z: LIKE is not supported on indexed fields in Big Objects.

C. SELECT Account__c, Program__c, Transaction_Date__c FROM Customer_Transaction__b WHERE Account__c = '001R000000302D3' AND Program__c INCLUDES ('Shoppers', 'Womens') AND Transaction_Date__c = 2019-05-31T00:00Z: INCLUDES is invalid for Big Object queries.

D. SELECT Account__c, Program__c, Transaction_Date__c FROM Customer_Transaction__b WHERE Account__c = '001R000000302D3' AND Program__c EXCLUDES ('Shoppers', 'Womens') AND Transaction_Date__c = 2019-05-31T00:00Z: EXCLUDES is not supported.

Reference:
Salesforce Big Objects Developer Guide

A developer created a JavaScript library that simplifies the development of repetitive tasks and features and uploaded the library as a static resource called rsutils in Salesforce. Another developer is coding a new Lightning web component (LWC) and wants to leverage the library, Which statement properly loads the static resource within the LWC?


A. import jsUtilities from ‘@salesforce/rescurceUr1/jaUtiles’;


B. lightning-require scripts="{|$Resource,jaUtils}"


C. const jsUtilivy = SA.get{'SResource.isUtils');


D. impore {jsUtilities} from ‘@salasforce/resourceUrl/jsUtils’;





D.
  impore {jsUtilities} from ‘@salasforce/resourceUrl/jsUtils’;

Explanation:

The developer uploaded a JavaScript library as a static resource named jsUtils. In a Lightning Web Component (LWC), static resources are accessed using the @salesforce/resourceUrl module to import the file dynamically, ensuring proper loading and usage.

Correct Answer: D. import { jsUtilities } from '@salesforce/resourceUrl/jsUtils';
Option D is correct. The import { jsUtilities } from '@salesforce/resourceUrl/jsUtils'; statement uses the @salesforce/resourceUrl module to import the jsUtils static resource, assigning it to jsUtilities. This allows the LWC to leverage the JavaScript library for repetitive tasks. The syntax follows LWC conventions, where the resource name matches the static resource key, and the import is used in the JavaScript file. This is a best practice for the Platform Developer II exam, ensuring modular and reusable code.

Incorrect Answers:

A. import jsUtilities from '@salesforce/resourceUrl/jaUtiles': Typo (jaUtiles vs. jsUtils) and incorrect import syntax (no {} for named imports).

B. lightning-require scripts="{!$Resource.jsUtils}"> Invalid for LWC; is an Aura component tag, not supported in LWC.

C. const jsUtility = SA.get{'$Resource.jsUtils');: SA.get is not a valid Salesforce API, and static resource access requires @salesforce/resourceUrl.

Reference:
Salesforce LWC Developer Guide: "Work with Static Resources".

Users report that a button on a custom Lightning web component (LWC) is not saving the data they enter. The button looks to be clicked, but the LWC simply sits there, seemingly doing nothing. What should the developer use to ensure error messages are properly displayed?


A. Add a try-catch block surrounding the DML statement.


B. Use the Database method with a110rNone Set to false.


C. Add the tag to the component.


D. Add JavaScript and HTML to display an error message.





A.
  Add a try-catch block surrounding the DML statement.

Explanation:

When a button in a Lightning Web Component (LWC) is clicked but appears to do nothing, the issue is often an unhandled exception in the Apex method performing the DML operation (e.g., insert or update). Without proper error handling, the LWC receives no feedback, leaving users unaware of the problem.

Option A: Add a try-catch block surrounding the DML statement.
Wrapping the DML operation in a try-catch block in the Apex method allows the developer to capture exceptions, such as DmlException, and return a user-friendly error message to the LWC. This message can then be displayed to the user, ensuring they understand why the save failed. This is a standard practice for robust error handling in Salesforce.

Option B: Use the Database method with allOrNone set to false.
Using Database methods (e.g., Database.insert with allOrNone=false) allows partial success in bulk DML operations but doesn’t directly address displaying error messages in the LWC. It requires additional logic to process errors and communicate them to the client, making it less suitable for this scenario.

Option C: Add the tag to the component.
The component is designed to display errors automatically for standard Salesforce form components (e.g., lightning-record-form). For custom Apex calls in an LWC, it won’t display errors unless paired with proper server-side error handling, making it insufficient alone.

Option D: Add JavaScript and HTML to display an error message.
While the LWC needs client-side logic to display errors, this option doesn’t address the server-side issue of capturing DML errors. Without proper Apex error handling, the client-side code lacks meaningful error information to show, making this incomplete.

Why Option A is Best:
The core issue is likely an unhandled DML exception in Apex, causing the LWC to fail silently. A try-catch block in the Apex method captures these errors and allows them to be sent to the LWC for display, providing clear feedback to the user.

Reference:
Salesforce Documentation - Apex Developer Guide
Salesforce Documentation - ShowToastEvent

The use of the transient keyword in Visualforce page controllers helps with which common performance issue?


A. Reduces load times


B. Improves page transfers


C. Reduces view state


D. Improves query performance





C.
  Reduces view state

Explanation:

The transient keyword in Visualforce page controllers is used to address performance issues related to view state in Salesforce. Below is an analysis of the options and why the transient keyword specifically helps with reducing view state.

Option A: Reduces load times While reducing view state can indirectly contribute to faster page load times by decreasing the amount of data transferred between the client and server, the primary purpose of the transient keyword is not to directly reduce load times. Load times can be influenced by many factors, such as server processing, network latency, or page rendering, which are not directly addressed by transient.

Option B: Improves page transfers The term "page transfers" is vague in the context of Visualforce. It could imply data transfer between client and server or navigation between pages. While reducing view state may improve the efficiency of data transfer, this is a secondary effect. The transient keyword’s direct impact is on view state size, not page transfers as a primary concern.

Option C: Reduces view state In Visualforce, the view state is the serialized data that maintains the state of a page (e.g., controller variables, form data) between client-server interactions. The transient keyword is used to mark variables in a controller or controller extension so they are not included in the view state. This reduces the size of the view state, which can otherwise grow large with complex pages or large datasets, leading to performance issues like slower page loads or hitting the view state size limit (135 KB in classic Visualforce). By declaring non-essential variables as transient, the developer ensures they are not serialized, directly addressing this common performance issue.

Option D: Improves query performance The transient keyword has no direct impact on query performance, which relates to the efficiency of SOQL queries or database operations. Query performance is optimized through techniques like selective queries, indexing, or limiting result sets, not through view state management.

Why Option C is Best:
The transient keyword is specifically designed to optimize Visualforce performance by reducing the view state size. When a variable is marked as transient, it is not persisted in the view state, meaning it is not sent to the client or stored on the server between page requests. This is particularly useful for variables that hold temporary or large data (e.g., lists used for processing but not needed in the UI). Reducing view state improves page performance and prevents errors related to exceeding the view state size limit, a common issue in Visualforce development.

Reference:
Visualforce Developer Guide: Transient Keyword
Explains how the transient keyword prevents variables from being included in the view state, reducing its size.

A developer creates a Lightning web component to allow a Contact to be quickly entered. However, error messages are not displayed.

Which component should the developer add to the form to display error messages?


A. apex:messages


B. lightning-messages


C. lightning-error


D. aura:messages





B.
  lightning-messages

Explanation:

The developer has created a Lightning Web Component (LWC) using lightning-record-edit-form to allow quick entry of a Contact record. However, error messages are not being displayed. The lightning-record-edit-form component is designed to handle standard Salesforce record operations (e.g., creating or updating records) and automatically generates error messages when validation fails or server-side operations encounter issues. To display these error messages to the user, the appropriate component must be added.

Option A: apex:messages The apex:messages component is used in Visualforce pages to display error, warning, or info messages from the Apex controller. It is not applicable in LWCs, which use Lightning components instead of Visualforce markup. This option is incorrect.

Option B: lightning-messages The lightning-messages component is specifically designed for LWCs to display error messages generated by components like lightning-record-edit-form, lightning-record-form, or lightning-record-view-form. When added to the form, it automatically renders any error messages related to field validation, required fields, or server-side failures (e.g., DML exceptions). This is the correct component to add to display error messages in this scenario.

Option C: lightning-error The lightning-error component is not a standard Salesforce component. It might be confused with custom implementations or misinterpretations, but it does not exist in the Salesforce Lightning Component Library. This option is incorrect.

Option D: aura:messages The aura:messages component is used in Aura components to display messages, including errors, but it is specific to the Aura framework, not LWCs. Since the developer is working with an LWC, this option is not applicable.

Why Option B is Best:
The lightning-record-edit-form component handles the underlying logic for creating or updating records and generates error messages when issues arise (e.g., missing required fields like LastName or Email, or server-side errors). Adding the lightning-messages component to the LWC template ensures these error messages are visually displayed to the user. This aligns with Salesforce best practices for providing feedback in Lightning components.

Reference:
Salesforce Documentation - lightning-record-edit-form:
Explains how this component generates error messages that can be displayed with lightning-messages.


Page 4 out of 17 Pages
Previous