SurveyCTO Repeat Group Using Previous Choices

Revision as of 11:29, 5 April 2018 by Admin (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Best Practice

There are many cases when you want to repeat a set of questions over previously selected responses, such as a set of crops cultivated or activities performed. Here we use an example based on a select_multiple question of 14 potential crops, where we want to ask follow up questions about those crops selected.

Both approaches require the use of the index() command, which yields the number of the repeat. Note that if NO CROPS is selected in the select_multiple question, the repeat groups are skipped. Also, it isn't possible to select NO CROPS and any other crops from the choices.

Code Example

Here is a code example showing the 2 main ways to achieve this. The comments in the labels of the calculate fields describe the steps taken in the SruveyCTO form.

1) Repeating for all options and adding a constraint inside the group

Here we code the repeat group count to cycle through all the possible options of the 'crop' choices - 14 in total - and add a constraint to the questions contained within the repeat group. The set up only needs a variable (${crop_name1}) to pull the crop name from the select_multiple options.

  • + easier to code
  • + output links the crop ID to the repeat count
  • - can create large number of fields/variables when there are a lot of choices, particularly for nested repeats (e.g. crops within plots within seasons) which can slow down form processing on the tablet

2) Only repeating for selected options

This method utilizes how the select_multiple fields are stored (e.g. 1 4 5). It selects the corresponding number (i.e. the crop ID) in the list in order through the selected-at(${crops2}, index()-1) calculate expression. Note that the '-1' is needed as the first field in the list is 0 (not 1), as in other programming languages like Python.

Once we know the crop ID, the crop name is pulled in the same manner as the other example. As the number of repeats is dynamic, we need to tell the repeat group to only repeat the number of times for which there are selected crops, which is: count-selected(${crops2}) . The setup of this method requires calculate fields for the crop ID and the crop name.

The main advantage in this approach is that it avoids the potential mass of missing data created when there are many choices to select from.

  • + more elegant, less missing data
  • + runs faster on large forms
  • - can be tricker to code
  • - output crop IDs do not line up with repeat count, need to account for this in data cleaning

Back to Parent

This article is part of the topic SurveyCTO Coding Practices