[Drupal] How to submit Drupal form to Hubspot?

| | 2 min read

To submit a Drupal form, suppose a registration form to Hubspot we need the following.

  • Hub spot Account
  • Hubspot Portal ID
  • Hubspot Form GUID
  • Hubspot Traffic Logging Code
  • Hubspot Form URL

If you don't have HubSpot account already, please sign up a free trial here. When you log into HubSpot, Hubspot Portal ID will be on the top right of your screen, in the application's menu bar. Also we need to add Hubspot tracking code to every page. For this purpose we can create block with title 'Hubspot traffic logging code'. Past the code in to the body of block. Make Text format is FULL HTML and set the block in footer of the pages. Hubspot Traffic Logging Code is,

<!-- Start of Async HubSpot Analytics Code -->
 <script type="text/javascript">
   (function(d,s,i,r) {
     if (d.getElementById(i)){return;}
     var n=d.createElement(s),e=d.getElementsByTagName(s)[0];
     n.id=i;n.src='//js.hs-analytics.net/analytics/'+(Math.ceil(new Date()/r)*r)+'/563815.js';
     e.parentNode.insertBefore(n, e);
   })(document,"script","hs-analytics",300000);
 </script>
<!-- End of Async HubSpot Analytics Code -->

Next thing we want to create a virtual form in Hubspot and get the form GUID from the URL (available in the address bar while editing the form). Then write function that will take form fields and submit it to form in Hubspot.

function hubspot_user_insert_lead($fields) {
  $fields['UserToken'] = isset($_COOKIE['hubspotutk']) ? $_COOKIE['hubspotutk'] : '';
  $fields['IPAddress'] = ip_address();
  $strPost = "Hubspot Form GUID";
  $portal_id = 'Hubspot Form GUID';
  $form_id = 
  $formURL = 'https://forms.hubspot.com/uploads/form/v2/'.$portal_id.'/'.$form_id;
  // Turn $fields into POST-compatible list of parameters
  foreach ($fields as $fieldName => $fieldValue) {
    $strPost .= urlencode($fieldName) . '=';
    $strPost .= urlencode($fieldValue);
    $strPost .= '&';
  }
  $strPost = rtrim($strPost, '&'); // nuke the final ampersand  
  // send POST data
  $r = drupal_http_request($formURL, array(
    'Content-Type' => 'application/x-www-form-urlencoded'),
    'POST', $strPost);
  
  return array('Data' => isset($r->data) ? $r->data : '',
    'Error' => isset($r->error) ? $r->error : '',
    'HTTPCode' => $r->code);
}

Now you can start using hubspot_user_insert_lead() in any form submit function. We can pass the form fields like this.

$values['firstname'] = $node->name;
$values['email'] = $node->email;
hubspot_user_insert_lead($values);

And thats it! Now when a form submit to your site, the results will be sent to your Hubspot virtual form as a lead. Do you have a requirement like this, get a quote now.

Its the time to clear your doubts, here.