Created
September 6, 2012 01:39
-
-
Save carwin/3649723 to your computer and use it in GitHub Desktop.
Drupal 7: hook_webform_submission_presave() to subscribe a user to a Simplenews newsletter with a conditional component.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
* Implementation of hook_webform_submission_presave() | |
* | |
* For a particular Webform node, use the submitted | |
* value of a component to determine whether or not | |
* the submitter will be subscribed to a Simplenews | |
* newsletter. | |
* | |
* Subscribe the user to the Simplenews newsletter | |
* using the value of the email component on the form. | |
* | |
* In this example, the Webform node id will be 42 | |
*/ | |
function yourmodulename_webform_submission_presave($node, &$submission){ | |
// Choose the webform ID | |
if($submission->nid == 42){ | |
/* | |
* Here I check my controlling component. | |
* I used a checkbox component to let users | |
* check a box if they wanted to subscribe. | |
* | |
* If the value is NULL, do nothing -- they | |
* don't want to subscribe. | |
*/ | |
if($submission->data[4][0] != NULL){ | |
/* | |
* The user wants to subscribe, use the value of | |
* this Webform's email component. | |
* In my form, I decided to have a hidden field that I would use | |
* to subscribe users. | |
*/ | |
// Set the email component value as the hidden field's value too. | |
$submission->data[5][0] = $submission->data[3][0]; | |
// Create the user array. | |
$user = array( | |
'snid' => '', | |
'activated' => '1', | |
'mail' => $submission->data[3][0], | |
'uid' => 0, | |
'language' => 'English', | |
); | |
// Create the subscription array. | |
$subscribe = array( | |
'snid' => '', | |
'tid' => 1, | |
'status' => 1, | |
'timestamp' => time(), | |
'source' => 'Your Module Name', | |
); | |
// Create an object out of the user array. | |
$subscriber = (object) $user; | |
if(simplenews_user_is_subscribed($subscriber->mail, 1)){ | |
// Do nothing, user is already subscribed | |
}else{ | |
// Subscribe them. | |
simplenews_subscriber_save($subscriber); | |
simplenews_subscribe_user($subscriber->mail, 1, FALSE, 'Your Module Name'); | |
} | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment