Expressions for common PR and PI tasks
Program rules are a common part of most tracker and event implementations in DHIS2, this how to guide serves as a repository for common PR tasks which are not immediately obvious how to solve using the built in functions available in DHIS2.
Date next year
This program rule expression allows you to assign a date to a field which is one year after the current date. There is a built in addDays function in DHIS2 which would allow you to add 365 days, however this does not work for leap years so may not be good enough depending on your use case.
Expression
d2:concatenate(d2:floor(d2:left(V{event_date}, 4))+1, d2:substring(V{event_date},5,7), d2:right(V{event_date},2))
How it works
d2:left(V{event_date}, 4)
: This takes the year part of the date so d2:left(2021-12-25, 4)
= 2021
d2:floor()
: This changes the value type from text to a number, so when you add 1 the you get 2022
not 20211
d2:substring(V{event_date},5,7)
: This gets the month portion of the date so d2:substring(2021-12-25,5,7)
= 12
d2:right(V{event_date},2))
: This gets the day portion of the date so d2:right(2021-12-25,2))
= 25
d2:concatenate()
: This joins all of the parts together giving 20221225
which at the time of writing DHIS2 automatically interprets correctly as the date 2022-12-25
Known issues
This will not work when the source date is the 29th February, because this date does not exist in the following year.
DHIS2 versions
All modern versions of DHIS2 (2.30+)
Count fields with values
The program rule expression allows you to get a count of the desired fields which have values in them.
Expression
d2:hasValue('programRuleVariable1Name') + d2:hasValue('programRuleVariable2Name') + ...
How it works
The d2:hasValue
function returns a true or false for each term, however the way these expressions are evaluated means that true is treated like 1 and false is treated like 0 when combined with arithmetic operators like +, -, *, /. This means true + false + true = 2 so you get a count of the fields with values.
Known issues
- Does not seem to work with number fields
- Works in program rules, but not program indicators
DHIS2 versions
All modern versions of DHIS2 (2.30+)