Popular Help Content

No popular content.
Go to start of banner

Overview

There are certain scenarios when you need to create more complex logic (than available in the built in logic builder (e.g. X statement is equal to Y value)) or more complex calculations. One option is to create a custom IF statement. An IF statement follows the construction, IF this, THEN this, OTHERWISE this. The format to express this kind of logic is the following: IF(evaluative statementresult if statement is true,result if statement is false).

For example, you could use an IF statement to conditionally store a value in a Hidden Value. Let's take an example where you register a client (a case) in a registration form and update the case property birth_facility. Later in the Follow Up form you want to update the case property birth_facility to the value of the question birth_facility_new IF the answer to change_facility is 'yes'; otherwise you want to leave it as the original value from the registration form.  You would do the following:

• Make sure that in the registration form you save birth_facility to the case

• In the follow up form create a second hidden value called birth_facility and enter an if statement in the "calculate" block: if(#form/change_facility = 'yes', #form/birth_facility, #case/birth_facility)

For further guidance, please see the Hidden Values Tutorial Part 3: If Statements

Operation ordering

Icon

Expressions in CommCare are evaluated left to right. The following example illustrates how this impacts expressions:

 `A and B or C`

is equivalent to:

 `((A and B) or C)`

Should you wish to evaluate expressions differently you must use parentheses to indicate which elements should be evaluated together e.g.:

 `A and (B or C)`

If "And" Statement

You might have multiple conditions for an IF statement, where you need to use the OR or AND functions. Below are examples that demonstrate how you can write your expressions. Note that there is no need to enter IF twice for each argument.

• Example with AND: if(#form/sys_bp >= 120 and #form/sys_bp <=139, 1, 0) where 1 refers to high risk

If "Or" Statement

Example with OR: if((#form/gender = "male" and #form/waist_circumference > 90) or (#form/gender = "female" and #form/waist_circumference > 85), 1, 0) where 1 refers to a high risk

Argh! I can't figure out what the mistake I made is!

Icon

You might get a generic error message and not understand why your complex statement is not working. Here are some common sticking points:

• Check all of your parentheses and quotation marks! They must all be in pairs. If you can't find it, try copying the statement into a tool like Notepad++ or Sublime Text as these tools can help you find missing parentheses