Pathfinder/m4change - fix saving location ids to SQL in m4change, move common code to helper functions

Additionally fixed issues mentioned in https://github.com/dimagi/commcare-hq/pull/2769.