---
title: "Custom Objects"
author: "kirenenko04"
date: "2014-07-28T15:09:15Z"
tags: []
categories: ["编程语言"]
slug: "custom-objects"
draft: false
lastmod: "2014-07-28T15:24:01Z"
id: 2097314
url: "https://kirenenko04.iteye.com/blog/2097314"
---

Custom Objects

 

**Defining Custom Objects**

 

You will learn how you can store data in a custom object so it can be **persistent**.

 

Custom objects (COs) extend the Demandware **data model**: they are basically **a new table** in the database where you specify the primary key and storage attributes (columns) that suit your business needs.

 

**IMPORTANT NOTE**

You should always consider **first** if a Demandware **System object** (Product, Catalog, etc) can be used instead of creating a custom object. Please do not abuse (滥用) the fact that you can create custom objects: they are best used to store static data (like configuration parameters), not for uncontrolled amounts of data (like analytics). Custom objects **searches can be slow** if the **data is large**. You should consider data growth and **cleanup** in your COs. Demandware Platform Governance has **quotas** （配额） around custom object API usage and data size which will be enforced in the future.

 

Custom object data types are created at the **organization level** and are therefore available for use in **all** storefronts within the organization. You use **two** different Business Manager modules to define and manage your custom objects:

 

**Custom Object Definitions**: allows naming, primary key and column specification.

Located under **Administration** **⇒ Site Development**

 

**Custom Object Editor**: allows instance **creation** and **editing**.

Located under **Site - &lt;site&gt;** **⇒ Custom Objects ⇒ Custom Object Editor.**

 

When **defining** the CO you specify the storage scope of the instances: **site** or **organization**. Organization custom objects can be used by *any* site, whereas（然而） *site* custom objects are created by **one site** and *cannot* be read by another. The CO type itself is always available to the entire organization. Also, you can **specify** if you want CO instances to be **replicable**: this means they can be copied from Staging to Production as part of the replication process.

 

**How-To : Create Custom Object Types**

 

01. Log into Business Manager.
02. Click Administration =&gt; Site Development =&gt; Custom Object Definitions
03. Click the **New** button to create a new custom object type.
04. Fill in the required fields for the custom object type
05. Click Apply.
06. Click the *Attribute Definitions* tab. You will notice default values created with your custom object type. These values cannot be changed once they are created
07. **Create the attributes** (values you wish to capture in the table) by clicking the ‘New’ button.
08. Specify a unique name in the ID field and then select the type of data being entered in the attribute from the Value Type drop-down menu
09. Click the Apply button.
10. When you are finished, click the ‘Back’ button to add another attribute.
11. When you are finished adding attribute definitions, you will need to create an Attribute Group. Click the ‘*Attribute Grouping*’ tab.
12. Enter a name for your grouping in the ID field and a name in the Name: field.
13. Click the Add button. You will need to add the field attributes next.
14. Click the Edit link to add field attributes to the group.
15. Click the 省略号 next to the ID: field to select field attributes.
16. Select the attributes you wish to add from the list by clicking in the checkbox next to each one. Then click the ‘Select’ button.

**To create a custom object instance manually in BM:**

1. Log into Business Manager.
2. Click the **site** you wish to manage the custom objects for.
3. Click Custom Objects -&gt; Custom Object Editor.
4. At the next window, **select** the **custom object type** you wish to manage from the drop-down list.
5. To create a new custom object, click the New button.
6. Enter data in each of the required fields and then click the **Apply** button.
7. You have now created a custom object. Click the **Back** button to exit the custom object editor.

**Using Demandware Script to Create Custom Objects**

The Demandware Script API provides the following **classes** in the **dw.object** package:

**CustomAttributes**: attributes defined by a user in the Business Manager to extend a system object or CO. Accessible via the syntax: co\_instance.custom.attribute

**CustomObject**: represents an instance of a CO

**CustomObjectMgr**: allows the **creation** of CO instances

**PersistentObject**: allows persistent (持久) storage

**ExtensibleObject**: allows custom attributes to be added (可扩展)

This is the inheritance tree for the CustomObject type:

Object –&gt; dw.object.PersistentObject -&gt; dw.object.ExtensibleObject  -&gt; dw.object.CustomObject (or dw.object.SystemObject)

 

This inheritance tree means that **COs** are **persisted** in the database and can have **custom attributes added** by an administrator or programmer in Business Manager. As you inspect (观察) the Demandware documentation you will see that commonly used classes like *dw.catalog.Product*, *dw.system.SitePreferences* and many others share this inheritance tree: objects of these class types are saved in the database and can be extended to store extra attributes.

 

The following usage of the **CustomObjectMgr** class allows creation of an instance of a CO by providing the *CO type* and the *primary key*:

CustomObjectMgr.createCustomObject("NewsletterSubscription", UUIDUtils.createUUID());

 

This will create an instance with a *system generated*, unique PK. You could also use:

CustomObjectMgr.createCustomObject("NewsletterSubscription", args.email));

 

This assumes that the **args.email** value should be a unique string every time a CO is created. Otherwise, a *duplicate PK* error will occur.

 

**Implicit Database Transaction Handling （隐式数据库事物处理）**

Database transaction handling in Demandware is handled by one of **two ways**: (隐式和显式)

**Implicit** – a transactional pipelet automatically begins a transaction. The transaction is **automatically** *committed to the database* when the pipelet returns **PIPELET\_NEXT**, otherwise the transaction is *rolled back*.

**Explicit** – the transaction is controlled via *properties of the **transition nodes***in the pipeline.

 

For **implicit transactions** to work, a pipelet that performs changes to the database must set its **Transactional property** equal to **true**. This becomes visible as a black "T" on the pipelet node in the pipeline.

 

If such a transactional pipelet is executed, a database transaction will be started **automatically** and will be committed implicitly at the end of this pipelet’s execution if the execution is *successful*.

 

**Create a custom object programmatically**

 

1. Create a custom object type in BM before creating a custom object programmatically. If you have not already done so, create your 2 custom object type as defined in the previous process step.
2. Create a script that uses the **dw.object.CustomObjectMgr** class to create a custom object:
   
   importPackage( dw.system );
   
   importPackage( dw.object );
   
   function execute( args : PipelineDictionary ) : Number
   
   {
   
       var co : CustomObject =
   
       **CustomObjectMgr.createCustomObject("NewsletterSubscription", args.email);**
   
       *co.**custom***.firstName = args.firstName;
   
       *co.**custom***.lastName = args.lastName;
   
       args.subscription = co;
   
       return PIPELET\_NEXT;
   
   }

Notice the use of the *custom* qualifier for all the custom attributes that you defined in the CO definition: without this qualifier the code will fail since the class **dw.object.CustomObject** does not have any **standard** attribute named *firstName*.

 

1. Edit the properties of the pipelet:
   
   1. ) Make it Transactional so it commits to the database.
   2. ) Assign all the corresponding form values to the pipelet inputs.
   3. ) Assign the subscription output to a Subscription object.
   4. ) Verify that all properties are correctly defined:

**Show Confirmation to the User** 

1. Modify the subscription confirmation template to use the Subscription object from the pdict:
   
   ${pdict.Subscription.custom.firstName}

**Troubleshooting**

1. Check to see if you imported **dw.object** package
2. Check to see if you have **marked** the **script node** as **Transactional**
3. Re-check the configuration of the script in Step 3d
4. Check if theNewsletterSubscription **Custom Object type** exists in the BM (‘N’ capital, ‘l’ small, ‘S’ capital).
5. Also check if string **attributes** “firstName”, “lastName” and “email” **exist** in it and are a part of an Attribute group.

**Custom Logging 自定义写日志**

The Demandware platform supports custom logging using log categories and severity levels as defined by the *Apache log4j* open source project

Log4j supports **multiple severities**(多重严重性) and categories of logging to allow the developer to capture debug messages at different levels of granularity（粒度）. The severity levels are:

**Debug &lt; Info &lt; Warn &lt; Error &lt; Fatal**

 

If custom logging is enabled for a **certain** severity level, then it is enabled for **higher severity levels as well**. Fatal and Error are **always** enabled and **cannot** be turned off

 

As for categories, the programmer can **define** as **many levels** of categories and subcategories as needed. Demandware does not impose（强行） a certain categorization; you decide how you want to organize your logging categories. For example:

- product
- product.import
- product.import.staging
  
   
  
  If logging is enabled for a category (say *product*), all its subcategories will also be enabled.
  
   
  
  **Examples**
  
   
  
  If **Warn** logging is enabled for "**product**":
- **Warn**, **Error** and **Fatal** errors are logged for "**product**" and all its **sub-categories**.
  
   
  
  If **Warn** logging is enabled for "**product**" and **Debug** for "**product.import**"

<!--THE END-->

- **Warn**, **Error** and **Fatal** messages are logged for "**product**" and all its **sub-categories**.
- **Debug** and **Info** are logged for "**product.import**" and all its **sub-categories**.

To write to a **custom log**, you will need to use the

**dw.system.Logger.getLogger()** factory method. This method **creates** a Logger object for a **specified** category

 

    var logger : Logger = **Logger.getLogger( “category" );**

    **logger.debug**("Input params received in pipelet  firstName: {0}\\n lastName: {1}\\n email: {2}",

                             args.firstName, args.lastName, args.email);

 

   try {

    … do something…

         return PIPELET\_NEXT;

    } catch (e) {

         **logger.warn**(“error description: {0}", e.causeMessage );

         return PIPELET\_ERROR;

    }

 

You can use the Logger object to write a message for a specific severity level: Logger.**error**(String msg).

The message uses the Java MessageFormat API, so you can specify placeholders. Typically these messages are **not** localized since they are read internally by site administrators, but they can be.

 

**Enabling Custom Logging**

In order to write to log files you will need to enable **Custom Log Settings** under **Administration** =&gt; **Operations** in BM:

 

**Enable Custom Logging in Business Manager**

1. Log into Business Manager.
2. Click **Administration** -&gt; **Operations** -&gt; **Custom Log Settings**.
3. Create a log category: type it on the field under a given severity(严重性), then, click **Add**.
4. **Enable** the checkbox next to the log category you wish to write to.
5. Click the **Apply** button.
6. Click **Log Debug to File** to allow debug messages to be written to a log for the next 10 minutes. Usually Debug and Info messages get written to memory only, and are visible via the Request Log tool.
7. Run the pipeline you wish to debug
8. Review the custom log file in Business Manager by clicking
   
   Administration –&gt; Site Development -&gt; Development Setup -&gt; Log Files.
9. Open the log file that was just created. Search for the file by date. The custom log file will be named something like
   
   ‘customdebug-177.aaaq.demandware.net-appserverxxxx.log’ .