verbb / formie

The most user-friendly forms plugin for Craft CMS.
Other
93 stars 69 forks source link

Form fields queries #1814

Closed DenyEs closed 2 months ago

DenyEs commented 2 months ago

Question

I've written a plugin for one of our clients to export submissions into the CSV as they require special formatting of certain fields. I am looping over submissions to create headings for the CSV which where I encountered an issue. Let's say I have 5 forms but there is submission only for one, it will only create headings in the export based on that one submission.

Is there a way to query Form object itself and get all fields rather than submissions? I tried multiple things and I can't seem to get it working.

Additional context

Using latest version of Craft and Formie

engram-design commented 2 months ago

I hope by "latest" you mean Craft 4 and Formie 2.1.10?

In that case, you should probably loop through each of your 5 forms, and each of their fields, creating a column for each. You can then fetch submissions for that form.

foreach ($forms as $form) {
    $submissions = Submission::find()->formId($form->id)->all();

    foreach ($submissions as $submission) {
        if ($fieldLayout = $form->getFormFieldLayout()) {
            foreach ($fieldLayout->getCustomFields() as $field) {
                $value = $submission->getFieldValue($field->handle);
                $valueForExport = $field->getValueForExport($value, $submission);

                $data[$form->handle . '_' . $field->handle] = $valueForExport;
            }
        }
    }
}

You probably can't do a single submission query and then loop through each form, as there's going to be issues if there are fields with the same handles for different forms.

Does that help?

DenyEs commented 2 months ago

Yes, apologies for that, I am on Craft 4.8.8 and Formie 2.1.10.

The problem I am having is that every time I call getFieldLayout(), it returns null.

There are fields with different handles but I have all that covered.

I do think I have a different solution for the problem tho, I will just have to test to see if it's going to work for my use case.

Cheers for that Josh

engram-design commented 2 months ago

Oh, my mistake, that should be getFormFieldLayout().

DenyEs commented 2 months ago

Managed to get it sorted in a bit of a different way which gave me exactly what I was after. Thank you for your help Josh :)