Skip to content

Commit

Permalink
Use relative references for repeats only.
Browse files Browse the repository at this point in the history
  • Loading branch information
ukanga committed Apr 3, 2018
1 parent 423160f commit 2af622a
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
18 changes: 18 additions & 0 deletions pyxform/survey.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,21 @@ def register_nsmap():
register_nsmap()


def is_parent_a_repeat(survey, xpath):
"""
Given a survey object and an xpath returns True if any parent is a repeat.
"""
parent_xpath = '/'.join(xpath.split('/')[:-1])
if not parent_xpath:
return False

repeats = [
item for item in survey.iter_descendants()
if item.get_xpath() == parent_xpath and item.type == 'repeat']

return any(repeats) or is_parent_a_repeat(survey, parent_xpath)


class Survey(Section):

FIELDS = Section.FIELDS.copy()
Expand Down Expand Up @@ -626,6 +641,9 @@ def _var_repl_function(self, matchobj):
if self._xpath[name] is None:
raise PyXFormError(intro + " There are multiple survey elements"
" with this name.")
# is parent a repeat?
if is_parent_a_repeat(self, self._xpath[name]):
return " current()/../" + name + " "

return " " + self._xpath[name] + " "

Expand Down
57 changes: 57 additions & 0 deletions pyxform/tests_v1/test_repeat.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# -*- coding: utf-8 -*-
"""
test_repeat.py
"""
from pyxform.tests_v1.pyxform_test_case import PyxformTestCase


class TestRepeat(PyxformTestCase):
"""
TestRepeat class.
"""
def test_repeat_relative_reference(self):
"""
Test relative reference in repeats.
"""
self.assertPyxformXform(
debug=True,
name="test_repeat",
md="""
| survey | | | | |
| | type | name | relevant | label |
| | text | Z | | Fruit |
| | begin repeat | section | | Section |
| | text | A | | A |
| | text | B | ${A}='oat' | B w ${A} |
| | end repeat | | | |
| | begin repeat | section2 | | Section 2 |
| | text | C | | C |
| | begin group | sectiona | | Section A |
| | text | D | | D |
| | text | E | ${D}='oat' | E w ${Z} |
| | end group | | | |
| | end repeat | | | |
""",
instance__contains=[
'<section jr:template="">',
'<A/>',
'<B/>',
'</section>',
],
model__contains=[
"""<bind nodeset="/test_repeat/section/A" """
"""type="string"/>""",
"""<bind nodeset="/test_repeat/section/B" """
"""relevant=" current()/../A ='oat'" """
"""type="string"/>""",
"""<bind nodeset="/test_repeat/section2/sectiona/E" """
"""relevant=" current()/../D ='oat'" type="string"/>"""
],
xml__contains=[
'<group ref="/test_repeat/section">',
'<label>Section</label>',
'</group>',
"""<label> B w <output value=" current()/../A "/> </label>""",
"""<label> E w <output value=" /test_repeat/Z "/> </label>"""
],
)

0 comments on commit 2af622a

Please sign in to comment.