Add Campaign Monitor Opt-In using Webform and Drupal

Tech Notes

Often clients as that we provide an opt in option on every kind of form a visitor could possibly fill in on a website - which is a Good Idea but often difficult. The thing that people don't tend to realise is that most forms are designed for one goal only - they send An email, they populate A database. Webform is a Drupal module for collecting and storing form submissions. There used to be a way to integrate an opt-in using the advanced processor. The function that this depended on has been deprecated in Webform 3.x as it was horribly insecure. Here is the first part of a quick recipe for getting a simple module up and running. There are lots of places to go with this (parsing Campaign monitor forms, integrating with the Campaign Monitor or Email marketing framework Drupal modules) but this is enough to get me up and running. It's based on work in the Drupal CM module issue queue

  1. If you haven't already create a CM subscriber list with custom fields as required
  2. Export the HTML required that you would normally drop into your website
  3. Install the Webform module
  4. Create the Webform that you need on your Drupal website
  5. When creating components in your Webform use the names from the CM form you exported for the webform field key replacing hyphens with underscores. eg: cm-name translates to cm_name which becomes my Name component's field key.
  6. Make sure you mark email as Mandatory.
  7. When creating Select options to match your custom fields in CM, recreate the list in the Options field in webform so that the option value and option text are in a pipe|separated list. 1047644|Afghanistan 1047645|Albania 1047646|Algeria
  8. Create the following module. Mines called webform_campaignmonitor
  9. In the file core = "6.x" dependencies[] = "webform" name = "Campaign Monitor for Webform" package = "Webform" version = "6.x-0.1"
  10. In the file webform_campaignmonitor.module <?php /* Implementation of hook_webform_submission_presave */ function webform_campaignmonitor_webform_submission_presave($node, &$submission) { //iterate over all webform components foreach ( $node->webform['components'] as $k=>$v ) { if ( strpos($v['form_key'], 'cm_') === 0 ) { if ( $submission->data[$k]['value'][0] ) { //webform doesn-t like hy-phens so replace under_scores $key = str_replace('_', '-', $v['form_key']); $results[$key] = $submission->data[$k]['value'][0]; } } } if ( $results['cm-opt-in'] ) { //send data to the form $url = ''; // the url to which your form submits $headers = array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'); $data = http_build_query($results, '', '&'); //TODO - error handling $req = drupal_http_request($url, $headers, 'POST', $data); drupal_set_message(t('You have been successfully subscribed to our newsletter.')); } } ?>