labd / wagtailstreamforms

What happened when a FormBuilder met a StreamField
http://wagtailstreamforms.readthedocs.io
MIT License
156 stars 80 forks source link

Unable to export form field through API fields #217

Open shinderucha opened 1 year ago

shinderucha commented 1 year ago

Hi All,

I am trying to choose a created form through WagtailFormBlock() using ChoiceBlock and then export the selected form through API fields. Code for ChoiceBlock is as below -

def getFormblockChoices(): choices = [] forms = Form.objects.all() for form in forms: choices.append((form.id, form.title)) return choices

class WagtailFormBlock(blocks.StructBlock):

FORMBLOCK_CHOICES = getFormblockChoices()

form = blocks.ChoiceBlock(choices=getFormblockChoices, required=False)
form_action = blocks.CharBlock(
    required=False,
    help_text=_(
        'The form post action. "" or "." for the current page or a url'))
form_reference = InfoBlock(
    required=False,
    help_text=_("This form will be given a unique reference once saved"), )

However, I am able to choose a form and publish the page but the fields are not visible through API.

Please let me know.

kirillwolkow commented 1 year ago

You can override the get_api_representation() method to get your fields. Here an example:

class StreamFormBlock(blocks.StructBlock): form = WagtailFormBlock()

def get_api_representation(self, value, context=None):
    value_dict = dict(value)
    form = model_to_dict(value_dict['form']['form'])
    fields = form['fields']

    return {
        'id': form['id'],
        'title': form['title'],
        'slug': form['slug'],
        'submit_button_text': form['submit_button_text'],
        'success_message': form['success_message'],
        'error_message': form['error_message'],
        'process_form_submission_hooks': ['save_form_submission_data'],
        'form_action': f"/api/v2/streamforms/{form['id']}/",
        'form_reference': value_dict['form']['form_reference'],
        'fields': fields._raw_data,
    }

class Meta:
    icon = "form"
    label = _("Stream Form")