Elastic Path Commerce Development

Dynamic Fields

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:

    <description><![CDATA[The configuration of a line item.]]></description>

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 Entites

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));     

Given fields, a set of configuration field definitions from the back-end, the above code loops through the collection and adds the dynamic property to the entity, with a key of the field code and an initial value of an empty String. The empty String ensures that the dynamic it appears in the form's JSON body.