Why an empty site preference returns null instead of empty string?

I have defined in Demandware a new custom preference of type text. The field is empty and when I try to request it using dw.system.Site.getCurrent().getCustomPreferenceValue('preference') it returns NULL instead of an empty string as I expected. Why?

Before answering the question, I must explain what the custom preferences are and how Demandware handles them.

The custom preferences are nothing more than custom attributes of the system object SitePreferences and the preference groups are just attribute groups of this object.

There are two ways to access the custom preference values:

dw.system.Site.getCurrent().preferences.custom.preferenceName;

or

dw.system.Site.getCurrent().getCustomPreferenceValue(id);

In both scenarios a NULL object is returned when the requested text field has no value. This is not very intuitive, because it is more logically meaningful Demandware to return an empty string. Moreover, Demandware does not return any custom property that has not value set. If you inspect the returned properties of

dw.system.Site.getCurrent().preferences.custom;

using the debugger you will notice that your preference is not there. You may expect to see it defined with NULL value but is actually not returned at all. You can't even check for the property exitance - let's say you defined a new custom property to the Product object named "colorSwatchURL" and you want to ensure that the metadata for it is imported and prevent nasty errors if it is missing.

This check will always fail:

var product = dw.catalog.ProductMgr.getProduct('123');
if (Object.prototype.hasOwnProperty.call(product.custom, 'colorSwatchURL')) {
    // display the swatch
}

No mater if the field is defined but empty or does not exists at all because the meta is missing - Demandware will not return it. At the same time when you request

return product.custom.colorSwatchURL;

it will not return udnefined as you request undefined attribute of a regular JavaScript object but NULL.

The same rule apply with the custom preferences.

Leave a Reply

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