The For loop

The for loop is used to perform a given number of iterations of the loop. The number of iterations is determined by the value of the loop-expression attribute, which looks something like this:

Figure 1. Simplified For Loop
<loop loop-type="for" loop-expression="numPeople">
  <question-page id="PersonDetailsPage" entity="Person">
    ...        
  </question-page>
</loop>

In other words, the number of times the PersonDetailsPage is displayed will be determined by the value of the answer to the numPeople control question. While this might work fine the first time through the loop, it is important to consider what happens when going through the loop a second or third time when reviewing or changing answers. For example, during the previous iterations, one or more persons may have been captured so it might make sense to loop through them rather than continuing to add new people.

In effect, the for loop becomes a for-each loop once some data has been entered in the entity its recording entries against. As such, it is necessary to give the for loop the same information given to a for-each loop: an entity to iterate over and an optional criteria. Once the entity is specified on the loop, there is no need to specify it for the pages within the loop so long as they are the same. The loop might look something like this:

Figure 2. For Loop with Entity and Criteria
<loop loop-type="for" loop-expression="numPeople"
        entity="Person" criteria="isPrimary==false">
  <question-page id="PersonDetailsPage">
    ...        
  </question-page>
</loop>

It is recommended when using for loops that the loop expression should be a simple expression referring just to the id of a question that is asked prior to the loop to determine the number of records to create. This question should be a control-question of type Integer.

This control-question will not be updated automatically, so it will be out of sync with the actual number of entities if entities are added or deleted through a summary page. Therefore its value shouldn't be used for anything other than the loop expression.

Once the loop has been started, it will be impossible to modify the value of this control-question, it will be read-only by default, unless the "hide-for-control-question" attribute has been set to true on the ieg-script element, in which case the label and value of the control-question will be hidden. The script designer should then ensure that the control-question is not the only question on the page where it is defined as this would lead to an empty page being displayed.

In practice, for loops have restricted application and therefore while loops are usually recommended for capturing information as their use can be more intuitive to the user.