fix bug with forms where data and ui have different hierarchies

and add tests

fixes: http://manage.dimagi.com/default.asp?117610
Pretty unclear exactly what is being tested here and impossible to tell by looking at the test data. Could you add a comment to give a bit more info?