Hubspot WordPress integration - captures ContactForm7 even when there is error

522 views Asked by At

I have the Hubspot integrated in my WordPress website. And it auto captures the forms in each page. The problem is, I have a ContactForm7 form. When user fills in the data and clicks the SUBMIT button of the form, it will get recorded in the Hubspot.

The issue is, when the ContactForm7 form is submitted and it gets processed at server side and has any errors, then also it gets recorded in the Hubspot as a new lead.

How it is supposed to work is, if the form is submitted and the ContactForm7 returns success message, then only the Hubspot should record it as a new lead.

Btw, ContactForm7 is sending data via AJAX.

Any pointers in solving this issue?

1

There are 1 answers

2
VonC On

There's no Hubspot form created inside the Hubspot account. We are collecting everything.
So basically we added only the embed code in the header.php like this:
<script type="text/javascript" id="hs-script-loader" async defer src="//js.hs-scripts.com/XXXXXXXXX.js"></script>

That means... you are using the HubSpot tracking code for automatic form submission.
We need to prevent the default HubSpot tracking of the ContactForm7 form and instead manually push the submission to HubSpot using their API when ContactForm7 submission is successful.

You would need to

  • Disable the auto capture feature in HubSpot: Go to HubSpot settings and disable the auto capture feature for forms. This will prevent HubSpot from automatically capturing form submissions.

  • Install and set up the CF7 to Webhook plugin: This plugin will allow you to send data from your ContactForm7 form to the HubSpot API when the form is successfully submitted. Install the CF7 to Webhook plugin from the WordPress plugin repository, and then set up a webhook in the plugin settings that points to the HubSpot form submission API.

  • HubSpot Form API: To use the HubSpot form submission API, you need to make a POST request to the following URL https://api.hsforms.com/submissions/v3/integration/submit/:portalId/:formGuid.
    Replace :portalId with your HubSpot portal ID and :formGuid with your HubSpot form GUID. The form data should be sent in the body of the POST request in JSON format.

  1. Prepare ContactForm7 form data for HubSpot API: Since HubSpot expects form data in a specific format, you need to format the ContactForm7 form data before sending it to the HubSpot API. The CF7 to Webhook plugin allows you to use filter hooks to modify the form data before sending it. Use the cf7_2_post_request_body filter hook to modify the form data.

Here's an example of how you can use this filter hook to format the form data:

add_filter('cf7_2_post_request_body', 'format_cf7_data_for_hubspot', 10, 3);
function format_cf7_data_for_hubspot($body, $submission, $instance) {
  // Get ContactForm7 form data
  $data = $submission->get_posted_data();
  
  // Prepare form data for HubSpot
  $hubspotData = array(
    'fields' => array(),
    'context' => array(
      // Put any data required by HubSpot context here
    ),
    'skipValidation' => true // Skip HubSpot form validation
  );

  // Convert form data to HubSpot format
  foreach ($data as $key => $value) {
    if (!empty($value) && !is_array($value)) {
      $hubspotData['fields'][] = array(
        'name' => $key,
        'value' => $value
      );
    }
  }

  // Return form data in JSON format
  return json_encode($hubspotData);
}
  1. Test: Finally, test your ContactForm7 form to see if the form submissions are being sent to HubSpot when the form is successfully submitted.

Make sure to replace placeholders with your actual HubSpot portal ID and form GUID in your webhook URL, and adapt the code above to your needs.

Also, make sure to add error handling code to deal with situations where the HubSpot API might be down or unreachable.


The Contact Form 7 (CF7) plugin triggers the 'wpcf7mailsent' event when a form has been successfully submitted. We can use this event to call the HubSpot Forms API to submit the form data only when this success event is triggered.

Using JavaScript and AJAX to call the HubSpot API on a successful CF7 form submission, that would be:

  • Include the jQuery library on your site if it's not already there. You can do this by adding the following code to your header.php or footer.php file in your theme directory:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.2/jquery.min.js"></script>
  • Add the following JavaScript code to your site:
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
    var inputs = event.detail.inputs;
    var data = {};

    for ( var i = 0; i < inputs.length; i++ ) {
        data[inputs[i].name] = inputs[i].value;
    }

    var settings = {
        "url": "https://api.hsforms.com/submissions/v3/integration/submit/YOUR_PORTAL_ID/YOUR_FORM_GUID",
        "method": "POST",
        "headers": {
            "Content-Type": "application/json"
        },
        "data": JSON.stringify({
            "fields": Object.keys(data).map(function(k) {
                return {
                    "name": k,
                    "value": data[k]
                };
            })
        })
    };

    $.ajax(settings).done(function (response) {
        console.log(response);
    });

}, false );
</script>

In the URL for the settings object, replace YOUR_PORTAL_ID and YOUR_FORM_GUID with your actual HubSpot portal ID and form GUID, respectively.

This code adds an event listener for the 'wpcf7mailsent' event, which is triggered when a CF7 form has been successfully submitted. It then prepares the form data and makes a POST request to the HubSpot Forms API to submit the form data. The form data is only submitted to HubSpot if the CF7 form submission is successful.

Make sure to handle any errors from the AJAX request to ensure that form submissions aren't lost if there's a problem with the HubSpot API.

Please note: It's generally a better practice to include scripts like this in an external .js file and enqueue it using the wp_enqueue_script() function on WordPress.
Also, adding scripts directly to your theme's files will mean that they'll be lost if the theme is updated. Consider creating a child theme to prevent this.


The wpcf7mailsent event is a custom event that's dispatched by the Contact Form 7 (CF7) plugin whenever a form is submitted successfully. By listening to this event with document.addEventListener('wpcf7mailsent', function() {...}), we can execute specific code only after a form has been successfully submitted.

This document.addEventListener listener waits for a successful form submission. When the wpcf7mailsent event is dispatched, it gathers the form data and sends it to HubSpot's API, ensuring that HubSpot only receives submissions when a CF7 form is submitted successfully.

Without this listener, the script would not be able to know when a form has been submitted successfully, and it wouldn't be able to send the form data to HubSpot's API at the right time.