5.6.3. foreach=”reference1”

Context

code instructions/foreach reference

Signature

foreach=”reference1”

Description

foreach=”reference1” instructs CodeComposer to generate code for each model reference of the current model object that has multiplicity 0..1 or 1..1.

Warning

foreach=”reference1” only works when a current model object is present in the context: either specify foreach=”object” or refer directly to an object with object=”<object name>” in your code instruction.

Note

CodeComposer will place the current model reference in the context with name modelReference for use in build-in functions, custom functions and snippets during generation.

Exceptions

Error

InvalidPatternException: invalid pattern: trying to create a <patternType> foreach reference but currentModelObject is null. Either specify a foreach=”object” in pattern or refer directly to a object of the model with the package=”<package name>” and object=”<object name>” statement.

Failed to produce code due to invalid pattern.

Example

CodeComposer input

Listing 5.52 src/codeinstruction/examples/example-code-instruction.xml
 1<java_package >
 2        <class  name="${object.name}"
 3                        visibility="public"
 4                        foreach="object"
 5        >
 6                <field  name="${reference.name}"
 7                                access="rw"
 8                                foreach="reference1"
 9                >
10                   <datatype>${reference.type}</datatype>
11                   <devcommentline>${fmsnippet.examples.exampleReferenceComment}</devcommentline>
12                </field>
13
14
15        </class>
16</java_package>
Listing 5.53 src/snippet/examples/exampleReference1Comment.ftl
1<#if !(modelReference)??>  <#stop "modelReference not found in context" ></#if>
2
3This is an example comment for a reference with multiplicity 0..1 or 1..1: ${modelReference.type} ${modelReference.name}.
Listing 5.54 src/model/model.xml
 1<model>
 2  <package>
 3        <object name="ExampleEmployee">
 4          <metadata></metadata>
 5          <attribute name="name" type="String" length="255" notnull="false">
 6                <metadata></metadata>
 7          </attribute>
 8          <reference name="manager" type="ExampleEmployee" multiplicity="0..1" notnull="false">
 9                <metadata></metadata>
10          </reference>
11          <reference name="colleagues" type="ExampleEmployee" multiplicity="0..n" notnull="false">
12                <metadata></metadata>
13          </reference>
14        </object>
15  </package>
16</model>

CodeComposer output

Listing 5.55 src/main/java/io/metafactory/codecomposer_reference/ExampleEmployee.java
1public class ExampleEmployee {
2   private ExampleEmployee manager; // This is an example comment for ExampleEmployee manager
3}