Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 28 ยท Platform APIs and Data

Custom Objects and System Object Extensions

Learn how Salesforce B2C Commerce stores your own data: custom attributes on system objects, custom object types, CustomObjectMgr, site preferences and metadata XML.

Sooner or later every Commerce Cloud project needs to store something the platform does not know about: a badge on a product, a gift-message flag on an order, a store-locator entry, the state of an export. B2C Commerce gives you two tools for this. You can extend a system object (add a custom attribute to Product, Order, Profile and so on), or you can define a brand-new custom object type that behaves like a small key-value table.

This lesson shows both, how they are declared in metadata XML, how you read and write them from the Script API, and, just as important, when to say no. Custom objects are convenient, but they are not a general-purpose database. The previous lesson, Customers, Sessions and Profiles, already touched custom attributes on the profile; here we go deeper.

The real platform code in this lesson (XML, dw.* scripts) cannot run on this site. Every example is a read-only block, and each lesson ends with live stand-ins written in plain JavaScript that model the idea. The stand-ins are not the Script API.

Three places to keep your own data

Need Tool Typical example
One extra field on something that already exists Custom attribute on a system object product.custom.badge, order.custom.giftMessage
A separate record with its own key Custom object One row per store, one per export state
A setting that applies to a site or to the organization Site preference (a custom attribute of the SitePreferences object) enableDeliveryBadge, an API base URL

All three are described in metadata: XML files that you import into an instance. The metadata is part of your code base, so it travels with your cartridge and every environment gets the same definitions.

Extending a system object

A system object is one of the platform's built-in types (Product, ProductLineItem, Basket, Order, Profile, Category, Site preferences, ...). You cannot change its built-in fields, but you can add custom attributes. They are declared in a file such as metadata/system-objecttype-extensions.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.demandware.com/xml/impex/metadata/2006-10-31">
    <type-extension type-id="Product">
        <custom-attribute-definitions>
            <attribute-definition attribute-id="badge">
                <display-name xml:lang="x-default">Badge</display-name>
                <type>enum-of-string</type>
                <mandatory-flag>false</mandatory-flag>
                <externally-managed-flag>false</externally-managed-flag>
                <value-definitions>
                    <value-definition default="true">
                        <value>none</value>
                    </value-definition>
                    <value-definition>
                        <value>new</value>
                    </value-definition>
                    <value-definition>
                        <value>sale</value>
                    </value-definition>
                </value-definitions>
            </attribute-definition>
        </custom-attribute-definitions>
        <group-definitions>
            <attribute-group group-id="Merchandising">
                <display-name xml:lang="x-default">Merchandising</display-name>
                <attribute attribute-id="badge"/>
            </attribute-group>
        </group-definitions>
    </type-extension>
</metadata>

The XML above is abbreviated to the parts that matter; a real export from Business Manager contains a few more optional elements. Three things to notice:

  • type decides what the field holds. Common types are string, text, html, int, double, boolean, date, datetime, email, enum-of-string, enum-of-int and the set-of-... variants for multiple values. Pick the narrowest one; Business Manager uses it to draw the right editor and to validate input.
  • attribute-id becomes the property name in the Script API. Keep it camelCase and meaningful; you cannot rename it later without migrating data.
  • Attribute groups only control how the attribute is arranged in Business Manager. Without a group, the attribute exists but merchants cannot see it in the editing UI.

You import this file in Business Manager under Administration > Site Development > Import & Export (as a metadata import, or inside a site import archive), or with a job step. After that, scripts can read the attribute:

JavaScript
// cartridge/scripts/helpers/badgeHelpers.js (read-only: needs the real platform)
'use strict';

function getBadge(product) {
    // custom attributes always live under the .custom property
    var badge = product.custom.badge;
    return badge && badge.value !== 'none' ? badge.value : null;
}

module.exports = { getBadge: getBadge };

For an enum-of-string attribute the value is an object with value and displayValue; for a plain string it is the string itself. For attributes that were never set, the property is null, not undefined. Always guard for it.

Writing needs a transaction

Reading is free. Writing a persistent object (a product, a customer, an order) must happen inside a transaction, otherwise the platform throws an error:

JavaScript
var Transaction = require('dw/system/Transaction');

Transaction.wrap(function () {
    order.custom.giftMessage = 'Happy birthday!';
});

Transaction.wrap commits when the callback returns and rolls back when it throws. Transactions were explained in The Script API and Common Classes. Keep such writes in small helper functions so that a failure never leaves an object half updated.

Custom object types

Sometimes the data does not belong to an existing object. A store locator needs one record per store; an integration needs to remember the last export state. That is the job of a custom object type, declared in custom-objecttype-definitions.xml:

XML
<?xml version="1.0" encoding="UTF-8"?>
<metadata xmlns="http://www.demandware.com/xml/impex/metadata/2006-10-31">
    <custom-type type-id="OrderExportState">
        <display-name xml:lang="x-default">Order export state</display-name>
        <staging-mode>no-staging</staging-mode>
        <storage-scope>site</storage-scope>
        <key-definition attribute-id="orderNo">
            <display-name xml:lang="x-default">Order number</display-name>
            <type>string</type>
            <min-length>1</min-length>
        </key-definition>
        <attribute-definitions>
            <attribute-definition attribute-id="status">
                <display-name xml:lang="x-default">Status</display-name>
                <type>string</type>
                <mandatory-flag>true</mandatory-flag>
            </attribute-definition>
            <attribute-definition attribute-id="attempts">
                <display-name xml:lang="x-default">Attempts</display-name>
                <type>int</type>
            </attribute-definition>
        </attribute-definitions>
    </custom-type>
</metadata>

Every custom object has exactly one key (key-definition), of type string or int, and the key is unique within the type. Two settings deserve a decision up front:

  • storage-scope: site keeps a separate set of objects per site, organization shares them across all sites of the realm.
  • staging-mode: whether the objects are copied between instances by data replication. For runtime data such as export states, use no-staging; replicating them from staging to production would be harmful.

You work with them through dw.object.CustomObjectMgr:

JavaScript
var CustomObjectMgr = require('dw/object/CustomObjectMgr');
var Transaction = require('dw/system/Transaction');

function recordExport(orderNo, status) {
    Transaction.wrap(function () {
        var entry = CustomObjectMgr.getCustomObject('OrderExportState', orderNo);
        if (!entry) {
            entry = CustomObjectMgr.createCustomObject('OrderExportState', orderNo);
            entry.custom.attempts = 0;
        }
        entry.custom.status = status;
        entry.custom.attempts = entry.custom.attempts + 1;
    });
}

// querying: a query string, a sort string, then bind values
var iterator = CustomObjectMgr.queryCustomObjects(
    'OrderExportState',
    'custom.status = {0}',
    'custom.attempts desc',
    'failed'
);
while (iterator.hasNext()) {
    var item = iterator.next();
    // ...
}
iterator.close();

getCustomObject returns null when the key does not exist, and createCustomObject fails if it does, which is why the sample checks first. The key itself is read-only after creation. Queries run against the database, so keep them simple and selective, and check the current documentation on query limits before you build a feature around a large result set.

flowchart TD
    A["Need to store data"] --> B{"Belongs to an<br/>existing object?"}
    B -->|"yes"| C["Custom attribute<br/>on the system object"]
    B -->|"no"| D{"Site-wide setting?"}
    D -->|"yes"| E["Site preference"]
    D -->|"no"| F{"Small, keyed,<br/>low volume?"}
    F -->|"yes"| G["Custom object type"]
    F -->|"no"| H["External system<br/>via a service"]

A quick decision path for where your data should live.

Site preferences

A site preference is a custom attribute on the special SitePreferences object. It is perfect for switches and settings that a merchant should be able to change without a deployment. You declare it as a type extension with type-id="SitePreferences" and read it like this:

JavaScript
var Site = require('dw/system/Site');

var enabled = Site.current.getCustomPreferenceValue('enableDeliveryBadge');
if (enabled) {
    // render the feature
}

Preferences are cached and evaluated per site, so they are cheap to read. Group them in a sensible Business Manager preference group so that a merchant can find them under Merchant Tools > Site Preferences > Custom Preferences. Never store secrets (API keys, passwords) in a plain preference: use the credentials of a service, which you will meet in Service Framework and Third-Party Integrations, or a password-typed attribute.

When not to use custom objects

Custom objects are easy, and that is the trap. They live in the same database as your shop, they have quotas, and they are not designed for analytics or heavy write loads. Avoid them when:

  • The volume is large or unbounded. Millions of log lines, one object per page view, or an event stream will hit storage limits and slow imports. Send those to an external system.
  • The data is highly relational. Custom objects have one key and no joins. If you need foreign keys and reporting, use a real database behind a service.
  • You need frequent updates from many requests. Writes take a transaction; hot records cause contention.
  • A custom attribute is enough. A flag on a product does not need its own object type.
  • You would copy staging data blindly. Remember staging-mode.

A good rule: custom objects are for configuration-like or reference data of modest size that the storefront reads far more often than it writes.

Live stand-ins

The first stand-in is a typed metadata store. It does what the platform does at a very small scale: attributes are declared with a type, values are validated against the declaration, and writes only happen inside a transaction that can roll back.

JS A typed metadata store with transactions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in models the choice between a custom attribute lookup that may be null and a site preference with a default. It shows the defensive style you need in real code.

JS Safe reads: null attributes and preference defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You want to store a 'gift message' on every order. What is the best fit?

    The data belongs to an existing object (the order) and has one value per order, so a custom attribute on Order is the simplest and most natural choice.
  2. 2. What happens if a script assigns order.custom.giftMessage outside a transaction?

    Changes to persistent objects must be wrapped, usually with Transaction.wrap, which commits on success and rolls back on an exception.
  3. 3. Which setting stops runtime data such as export states from being copied from staging to production?

    staging-mode controls replication between instances. Runtime and integration state should use no-staging.
  4. 4. Which workload is a poor match for custom objects?

    High-volume, append-only event data does not belong in the shop database. Send it to an external system through a service.

Summary

  • Add fields to existing objects with custom attributes declared in system-objecttype-extensions.xml; read them via object.custom.attributeId.
  • Create new keyed records with custom object types (custom-objecttype-definitions.xml) and use CustomObjectMgr to create, get, query and remove them.
  • Site preferences are custom attributes of SitePreferences, read with Site.current.getCustomPreferenceValue.
  • Writes to persistent objects need Transaction.wrap; unset attributes read as null.
  • Choose storage-scope and staging-mode deliberately, and keep large or relational data outside the platform.

Next, learn how to plug your own logic into the platform's built-in processes in Hooks and Extension Mechanisms.