How to choose email recipient in Contact Form 7 based on address state input in form and save to database [closed]

Thanks to Michael Simpson, from Contact Form DB. The solution is listed (kind of hidden) on the Contact Form DB website in the article – CF7 Menus with Pipes

Add to functions.php

function myFilter($formData) {
// Change $formData
return $formData; // be sure to return it
}

add_filter('cfdb_form_data', 'myFilter');

function location_form_handler($formData)
{
$formName="ExtendedContact"; // change this to your form's name
$fieldName="state"; // change this to your field's name
if ($formData && $formName == $formData->title && $formData->scanned_form_tags) {
    $emailSelected = $formData->posted_data[$fieldName];
    $valueSelected = null;
    foreach ($formData->scanned_form_tags as $tag) {
        if ($tag['name'] == $fieldName) {
            foreach ($tag['raw_values'] as $rawValue) {
                // value|email
                $valuesArray = explode('|', $rawValue);
                if (count($valuesArray) == 2 && $valuesArray[1] == $emailSelected) {
                    $valueSelected = $valuesArray[0];
                    break;
                }
            }
        }
        if ($valueSelected != null) {
            break;
        }
    }
    if ($valueSelected != null) {
        $formData->posted_data[$fieldName] = $valueSelected;
        $formData->posted_data[$fieldName . '_email'] = $emailSelected;
    }
}
return $formData;
}
add_filter('cfdb_form_data', 'location_form_handler');

This will create an entry in the database with the state name (field before the pipe) as state and a second field (email address after the pipe) with the associated email address as state_email.

Finally, update the form definition in Contact Form 7 thus: [state_email]

NOTE

I also want to mention, in case someone else comes across this situation –

In my form, visitors who fill out the form select the state they are located in, then the salesperson who is responsible for that state receives the email. As well, I needed the email to be sent to a central (corporate) email address.

However, not all states have an assigned salesperson, being the company focuses on the mid-west.

With Contact Form 7, if the email address after the pipe was empty, emails would not be sent at all. The method outlined by Michael actually allows an empty field after the pipe.

I set up “Mail” in the form to send to the central email and “Mail (2)” to send to the salesperson (if one exists).

Leave a Comment