MODX Community

Using formIt email hook with dinamically generated fields

Hi there, I developed a form that gives the user the chance to add multiple sections, each section’s input has a counter at the end of the input fields to be able to differentiate them, this is an example:

<input autocomplete="off" id="delivery-town0" name="delivery-town0" type="text">

And the form can end up having as many inputs as the user wants

What I’m trying to achieve is to shown all the inputs filled by the user on the email but haven’t found a way to do so.

Already tried adding some js script to the mail template with no luck, not even the document.write gets printed

    document.write('aca volvi a escribir!');
    for (conta = 0; conta < 2; conta++) {
        let delAddressVarName = 'delivery-address1' + conta;
        let internalVar = [[+delAddressVarName]];

What could be a solution? I’m guessing calling a snippet inside the template, but would it be processed? any ideas are welcome

You could create a custom hook that runs before the email is sent. In the hook, you can read all the form fields with $hook->getValues(). You could then combine all your delivery-town0, delivery-town1, …-fields into one string and set it as a new field with $hook->setValue(). In the email-template you can then use this new field as a placeholder.

Here some untested code to illustrate what I mean:

$formFields = $hook->getValues(); //get all form fields

$counter = 0;
$deliveryTown = array();
while (array_key_exists('delivery-town'.$counter, $formFields)) {
  $deliveryTown[] = $formFields['delivery-town'.$counter];

$hook->setValue('delivery_town_all', implode(',',$deliveryTown));
return true;
1 Like

Thanks a lot, makes perfect sense, will try that

Hi @camicase82, we’ve been working on an extra for Formit to do just this. Its not quite ready but if you want to give it a try let me know and i’ll send you the package and readme. Works by adding a repeater element to your email template that loops through all submitted form fields (with some exceptions).

1 Like

I’ve used JavaScript code that converts the entire form to a JSON string. It doesn’t care what the form looks like and will handle all possible form elements (e.g., textareas, radios, checkboxes, etc.).

I use it to post the result to a processor when the form is submitted, but it could be modified to create a single input containing the JSON so you could handle it in a FormIt postHook. I can try to locate the source if you’re interested, although it may be overkill for what you’re doing.

1 Like

Hi there, sounds good, pls share it to and ill take a look

posibly, Im guessing you added the js before actually procesing the formIt hooks?