CommCare – Configure Case List to Autoselect Child Case in Advanced Modules

commcare

I want to set up an advanced module form such that the user selects a parent case and the form auto-selects the child case to update. I see that in this documentation this should be possible with auto-select cases, however I'm not exactly sure how I should configure saving a case ID such that this functionality will work. How should I set up my case list configuration to auto-select the child case based on the parent case?

Best Answer

I'm going to assume I have a case structure where we have a "client" case and under the client a "pregnancy" case. A critical assumption for auto-selection to make sense is that there will always be 1 and only 1 pregnancy case per client case. You can ensure that this is true by filtering the form so that it only shows for clients who have a pregnancy case.

I assume that I already have an action for the client case with case tag load_client_1.

Add an action of type "Automatic Case Selection". You want to use Autoselect mode "Raw". The Expected Case Type is "pregnancy" and the Case Tag is whatever you want to use to reference this case in the form (example: autoload_pregnancy_2).

Here is the XPath function: instance('casedb')/casedb/case[index/parent=instance('commcaresession')/session/data/case_id_load_client_1][@status='open'][@case_type='pregnancy'][1]/@case_id

This expression grabs the first open case from the casedb whose parent id matches the loaded client case's id. The [1] filter is important to protect against throwing an error if for some reason a client were to end up with 2 pregnancy child cases (this is technically possible in bad connectivity with case sharing).

If you have a host-extension relationship rather than parent-child, just replace the index/parent above with index/host.