Get Product Field Data Related To The Cart Items In Custom Components For Cart Page On Salesforce B2B & D2C Commerce Cloud LWR
๐ Use Case
There is a commerce storefront built on Salesforce Commerce Cloud using Experience Cloud LWR. Each product available in the storefront has some custom data stored in fields on the Product object record. There is a need to build a custom component for the cart page, the component needs to analyze the cart items and the data stored in the product related to the cart item and show a message to the user.
โก๏ธ Storefront API Wire Adapters To The Rescue
In our previous blog post - How To Build Real-Time Components For Your Cart Page On Salesforce B2B & D2C Commerce Cloud LWR we saw how Storefront API Wire Adapters help build custom Lightning Web Components for B2B & D2C Commerce Storefronts - https://developer.salesforce.com/docs/atlas.en-us.b2b_b2c_comm_dev.meta/b2b_b2c_comm_dev/b2b_b2c_comm_display_lwc_apis.htm
๐ฎ Let's Build
To get the info we need, the Wire Adapter - CartItemsAdapter
is perfect.
cartItemsWithProductsCustomFieldData.js
import { LightningElement, track, wire } from 'lwc';
// Importing the Cart Items Wire Adapter from the 'commerce/cartApi' module
import { CartItemsAdapter } from "commerce/cartApi";
export default class CartItemsWithProductsCustomFieldData extends LightningElement {
// Declaring a tracked property to store the cart item data
@track cartItems;
// Using the @wire decorator to invoke the CartItemsAdapter function and fetch the cart item data
@wire(CartItemsAdapter, {
// Specify Product2 object fields API names comma-separated
// Want all fields from the Product2 object? then specify - productFieldNames: ["*"]
productFieldNames: ["FIELD_1_API_NAME__c","FIELD_2_API_NAME__c"]
})
getCartItems({ data, error }) {
// Checking if data is available
if (data) {
// Logging the cart items data to the console
console.log('๐๏ธ CartItemsAdapter data ', data);
// Setting the cartItems variable with the retrieved data
this.cartItems = data;
// Checking if there is an error
} else if (error) {
// Logging the error to the console
console.error('CartItemsAdapter error ', error);
}
}
}
The data returned by CartItemsAdapter
contains Cart Item Collection - https://developer.salesforce.com/docs/atlas.en-us.chatterapi.meta/chatterapi/connect_responses_cart_item_collection.htm
Among other properties, the JSON returned has
cartItems
- an array of items in the cartcartSummary
- summary information of the cart
Each item in the cartItems
array has the property cartItem
with all the data related to the cart item. To access the data of the product2 record that is related to the cart item, use the productDetails.fields
property. So you can reference it like โก๏ธ cartItem.productDetails.fields