Formit with JSON/CSV Attachment

Hi guys.
Has anyone tried submitting data through formit and tried creating a csv/json file from the data and attaching it to the email that’s sent?
Do you guys have sample code you can share?

the scenario we’re trying to work with is this:

  1. user fills up formit form and submits it
  2. the formit data gets translated to json
  3. a json file is created from #2
  4. the json file is attached to the formit email that’s sent to the set recipient.

Would really appreciate any help!
Thank you!

If shortly you should write custom hook for this, create file, attach and send.
Not sure how to attach this to basic Formit message sending directly so I’ve done it via my custom hook also, basic email was interrupted (just remove email hook from &hooks=`` parameter). This is quite simple if you familiar with PHP. Probably I can share some code with you tomorrow.

Just for reference. https://docs.modx.com/extras/revo/formit

1 Like

Hey man! Thank you. Would love to wait and see your code. appreciate the response.

Try this. Just add it as a hook before the email hook.

<?php
// Code originated from the MODX community: 
// https://tinyurl.com/y2v8wuao

// Get all form values
$formValues = $hook->getValues();

// Create key/value pairs
foreach ($formValues as $key => $value) {
	$formFields[] = $key;
	$formFieldsValues[] = $value;
}

// Set storage path for CSV
$attachment_path = 'assets/components/form_csvs/';

// File name sanity check
$csv_name1 = str_replace(' ', '_', $formValues['name']);
$csv_name2 = str_replace('/[^A-Za-z]+/', '_', $csv_name1) . '_' . time();

// Create CSV
$fp = fopen($attachment_path . $csv_name2 . '.csv', 'a');

// Write values to CSV
fputcsv($fp, $formFields);
fputcsv($fp, $formFieldsValues);
fclose($fp);

// Attach CSV to email 
$hook->modx->getService('mail', 'mail.modPHPMailer');
$hook->modx->mail->mailer->AddAttachment($attachment_path . $csv_name2 . '.csv');

// Continue to next hook
return true;
1 Like

This is sick.
thanks man @lkfranklin!
Will try it now.