I am trying to pull the latest Patient Instructions observation term by location of care. Below is the function I am using. For some reason this pulls the oldest observation term. I am needing it to pull the newest. I tried to use a sort but It is sorting the contents of the observation term in alphabetical order. Is there a way to make these sort by date?
fn PT_INST_BY_LOC(){INSTLIST = GETFIELD(LIST_OBS("INSTRUCTIONS","signed","delimited","value"),"|","")
OBSSIZE = SIZE(INSTLIST)
COUNT
GETOBS
RETURNINST = ""
FOR COUNT = 1, COUNT <= OBSSIZE, COUNT = COUNT + 1 DO
GETOBS = GETFIELD(INSTLIST[COUNT],"^","")
IF GETOBS[9] = USER.CURLOCATIONNAME
THEN
RETURNINST = "Date of Visit: " + GETOBS[2] + HRET + "Location of Care: " + GETOBS[9] + HRET + GETOBS[1]
ELSE ""
ENDIF
ENDFOR
RETURNINST}
Look closely at your code. In it, the function is doing exactly what you instruct it to do - loop through the entire obs list and return the last entry for the LOC found. To return the first instance, you need to exit the loop when it is found.
Change would look like this:
IF GETOBS[9] = USER.CURLOCATIONNAME THEN
RETURNINST = "Date of Visit: " + GETOBS[2] + HRET + "Location of Care: " + GETOBS[9] + HRET + GETOBS[1]
BREAK
ELSE ""
ENDIF
your FOR loop starts at 1, and then goes up, but this function returns obs starting with newest, and then moves down. A simple solution would be to put the word BREAK after you find the first instance of the correct obs term, and it will stop your for loop and finish the code:
FOR COUNT = 1, COUNT <= OBSSIZE, COUNT = COUNT + 1 DO
GETOBS = GETFIELD(INSTLIST[COUNT],"^","")
IF GETOBS[9] = USER.CURLOCATIONNAME
THEN
RETURNINST = "Date of Visit: " + GETOBS[2] + HRET + "Location of Care: " + GETOBS[9] + HRET + GETOBS[1]
BREAK
ELSE RETURNINST = ""
ENDIF
ENDFOR
This code is the most efficient, as it stops the loop from going through all the obs after you get your first match.
Alternatively, you could change your for loop like so:
FOR COUNT = OBSSIZE, COUNT >= 1, COUNT = COUNT - 1 DO
This will start the loop at the oldest, and go through all of them. Since you overwrite the variable RETURNINST every you go through the loop, it will update to the newest value.
Let me know if you have any questions.
Thank you,
Daniel Carpenter
Perfect yes! Makes complete sense I need to stop the loop once the first value is found. Thanks for the help!
Thank you Daniel! works perfect. I appreciate the help.