Dynamic Fields
Typically a resource entity in Cortex will have explicitly defined properties for holding its information. It may be necessary, however, for an entity’s properties to be more dynamic, varying from instance to instance of that entity, most likely driven by a back-end data source. To do this, use dynamic fields.
An example of dynamic fields in use would be a Line Item Configuration entity. The entity defines the configuration for an item in the shopping cart, but the configuration is defined in the back end, and is specific to the type of item.
API Definition
To include dynamic properties in an entity, include the <dynamic/>
tag in the resource’s API definition XML file:
<entity>
<name>line-item-configuration</name>
<description><![CDATA[The configuration of a line item.]]></description>
<dynamic/>
</entity>
Generated Entity
The entity generated from the XML includes methods that allow access to reading and creating these properties.
For example, the below provides a map of of the dynamic property name to the value:
@Property(name = DYNAMIC_PROPERTY)
Map<String, String> getDynamicProperties();
Continuing, the method below is part of the entity’s builder, and provides a way to add the property value for a given key:
@Property(name = DYNAMIC_PROPERTY)
BUILDER addingProperty(String key, String value);
Using Dynamic Entities
Initializing the properties
Dynamic properties are normally added to the entity when that entity is created.
For example, if we had a configurable line item being added to the cart, when the item details are read from the back-end, a set of configuration options are also read. We can then initialize the dynamic properties as follows:
final LineItemConfigurationEntity.Builder configBuilder = LineItemConfigurationEntity.builder();
fields.forEach(field -> configBuilder.addingProperty(field.getCode(), StringUtils.EMPTY));
For each field, the code loops through the collection of configuration field
definitions and adds the dynamic property to the entity. The dynamic property has a key. The key consists of the field
code and an initial value of an empty String
. The empty String
ensures that the dynamic property appears in the form’s JSON body.