Snippet to Count form submission

Hello all! I have built forms using Formalicious and they work perfect. I am trying to create a snippet that will count the amount of times a form is submitted. The snippet is called like so - [[The form has been submitted [[!FormSubmissionCounter]] times.]] and the snippet is:
// Define the form alias
$formAlias = ‘Risky User’;

// Get the current submission count from a MODx system setting
$submissionCount = $modx->getOption(‘form_submission_count’, null, 0);

// Increment the submission count by 1

// Update the MODx system setting with the new count
$modx->setOption(‘form_submission_count’, $submissionCount);

// Output the submission count
return $submissionCount;]]

If anyone could take a look and help me to figure out why the counter stays at 1, that would be amazing.

setOption doesn’t change the value in the database (or in the cache).

If you really want to use a system setting to save the counter, you probably have to use code like this to change the value:

$setting = $modx->getObject('modSystemSetting', 'form_submission_count');
$setting->set('value', $submissionCount);

Also, system settings get cached. If you don’t clear the cache after updating the system setting, you’ll have to read the value directly from the database table (instead of using getOption).

BTW: If you want a correct counter, you should use a custom FormIt hook to change the value (after the form is sent) and a different snippet to output the value.

Thank you sir, I will have to get into this a little more. I’ve read through the material and tbh never have I made a FormIt hook before. I was hoping for an easy snippet but it looks like I have some reading to do. Thank you again!

In this case (when you just want to update a value) you can use normal snippet code. (No reading needed.)

Just remember to put the line return true; at the end, so that FormIt knows that the hook ran without errors (and the form sending doesn’t get aborted.)

Code like this should work:

$setting = $modx->getObject('modSystemSetting', 'form_submission_count');
if ($setting){
    $submissionCount = (int) $setting->get('value');
    $setting->set('value', $submissionCount);
return true;

It’s just that if you call the snippet (that updates the counter) directly on a page ([[!FormSubmissionCounter]]), then every time you refresh the page the count gets incremented (even if no form is sent).