Incrementing a counter
Overview
It may be useful to increment counters in a case values, the typical example being the number of visits or consultations a patient received. The case stores the number of consultations received and each form stores a number of the consultation received at that time. Such counters are implemented with a couple of hidden values in the form and a single case value.
General Approach
We will walk through a very simple example where we count the number of times that a home visit form has been completed.
Set up the Form
The visit form will need to have a hidden value.
Hidden value name | Description | Calculate Condition | Explanation of Calculation Condition |
---|---|---|---|
count | Each time the form is opened, this hidden value will calculate how many times the form has been filled out | coalesce(#case/visit_count, 0) + 1 | This hidden value will use coalesce to determine whether the case property visit_count has any value. If it does, it will add 1 to it, if it does not then it will take 0 and add 1 to that. You can imagine the first time the form is completed it will add 1 to 0 = 1 The second time it will take the case property value (1) and add 1 = 2 And so on... |
CommCare Functions: Coalesce
Icon
This example uses a function called coalesce. You can read more about CommCare Functions but here is the basic information about how this function works:
coalesce
Behavior: Useful for choosing which of two values to return. Will return the non-empty value. If both are not null, will return the first argument.
Return: One of the values
Arguments: The two values to be coalesced
Syntax: coalesce(value_1, value_2).
Example: This is useful if you want to use a default value when referring to a question which may or may not have been answered. Ex. coalesce(#form/my_question, "my default value").
Set up the Case Management
After you form is set up you will need to link your case properties. You will want to take the value of home_visits each time, add one, and save it to the case again.
Example: Counting ANC Visits
Let's take an example of Ante Natal Care (ANC) visits.
Create a hidden value (
anc_number)
to compute the current ANC numberby
adding 1 to the case propertyanc_number
Since the case property
anc_number
can be blank in the case of a first ANC, we need to use the coalesce function:coalesce(#case/anc_number, 0) + 1
Explained Step by Step
To count or keep track of ANC visits in follow-up forms, do this…
Create Hidden Value anc_number
Set up your case management to save anc_number to the case
In the form question anc_number, in the calculate condition, type: coalesce(#case/anc_number,0)+1