oTree Forum >

Is it possible to use varying numbers of fields (via get_form_fields) and still position individually?

#1 by mitnec

I'm stuck.

I'd like to have a get_form_fields that returns from 3-12 fields for a particular page. Each field goes with an image (path supplied via vars_for_template). I'd like to position everything using a for loop on the template:

<!-- Make a for loop that generates each image / blank pair -->
{{ for prompt in player.prompts_subset }}
    <img src="{{ prompt.File_name }}"/>
    {{ formfield 'SOMETHING' }}
{{ endfor }}

But I can't see how to use varying numbers of fields delivered by get_form_fields without using {{ formfields }} (plural). Is there a way to do it?

If not, I can hard-code the max number and hide stuff I don't want people to see, but that seems inelegant...

#2 by Chris_oTree

def prompts_subset(player: Player):
    # just an example
    return [dict(field_name='f1', file_name='f1_file'), dict(field_name='f1', file_name='f2_file')]

class MyPage(Page):
    def get_form_fields(player: Player):
        return [prompt['field_name'] for prompt in prompts_subset(player)]

    def vars_for_template(player: Player):
        return dict(prompts=prompts_subset(player))

{{ for prompt in prompts }}
    <img src="{{ prompt.file_name }}"/>
    {{ formfield prompt.field_name }}
{{ endfor }}

Write a reply

Set forum username