Hi folks -- Here is my saga about problems calculating an "age" value...
which would *normally *be a "your first day learning CommCare" task!
I have a field that wants to calculate the age of a client, based on
knowing their birthday.
I'm in thailand, so I can't use the normal date picker field for the client
birthday, because thailand uses the buddhist year which is western year
plus 543. (so 2525 = 1982.)
So, I have three numerical fields, one for month, date, and year. (This is
useful for other reasons too, I need those numbers for other purposes.
SO, to have a birthdate field, after subtracting the 543, I then CONCAT
together the YYYY-MM-DD and so store it in a calculated value called
peer-birthdate, so I have a nice normal date field for their birthdate.
Works fine.
BUT THEN, thanks to a new requirement, I need to calculate the AGE of that
client today. So I have a field that takes that birthday and says:
int( ( today() - date(/data/peer-birthdate) ) div 365 )
--> BUUUTTT, that's not good because the moment you run the form, there is
an initial BANK in the three fields for birth year, month, date... SO there
is an initial moment when my concatted peer-birthdate field is merely "--"
... which is not yet a problem because it's just temporarily like that ...
but it becomes a problem in my AGE calculation field because the date()
function crashes the whole app when it is, for that first minute, fed a
text string that is merely "--".
--> SO, I figure, fine, I will throw an IF statement in there to ensure
that the peer-birthdate string is a full 10 digits long, thus ensuring that
it does not evaluate the date() function until YYYY-MM-DD is fully
assembled.
--> BUT NO!!! Because then, when the app is running on the phone, it's all
fine and the if() statement keeps it from crashing at the beginning. But
then the moment I type JUST ONE NUMBER into the birth year field... for
instance I want to write 2525 so I start to type the number 2... and it
IMMEDIATELY evaluates the 2, sends the results through the chain of
expressions in the various hidden value fields, and thanks to the
subtraction of 543, the birth year becomes a negative number, -541 ...
which in fact is 4 characters long so my birthdate string becomes
"-541-12-24" ... which is ten characters long, so it passes the if
statement and the date field tries it and my app crashes!
(1) My main reaction is, GOL DANG! While I try to just type a single
birth year in there, does it really need to immediately evaluate all
expressions in real time on the fly like that? Someday I may be glad that
it does, but man, right now I wish it would let me type my birth year in
and then evaluate things when I am done?
(2) Secondly, I will probably find a better thing for the IF statement and
this will work, but a smart commcare programmer sees what seems like the
"best practice" solution for this kind of error-avoidance screening, let me
know!!
THANKS!
Eric