Drupal 7, Mailchimp module 3.4
$list_id = '12345asd'; // use mailchimp_get_lists() and look for 'id'
$email = '[email protected]';
if ( mailchimp_subscribe (
$list_id,
$email,
array (
'EMAIL' => $email,
'FNAME' => $first_name, // fields in your mailchimp list
'LNAME' => $last_name,
),
false,
false
)) {
drupal_set_message ( t('Thank you. From now you will receive our promo materials'));
} else {
drupal_set_message ( 'Error occurred while adding your email to subscribe list', 'error' );
}
NOTE: If mailchimp will deside that your email is invalid module will only put watchdog error. To grab that error and display you can patch mailchimp.module
find function mailchimp_subscribe_process and goto approx line 412. and add drupal_set_messaga or whatewer you want.
Approach without patching module (but it's too hacky)
$list_id = '12345asd'; // use mailchimp_get_lists() and look for 'id'
$email = '[email protected]';
if ( mailchimp_subscribe (
$list_id,
$email,
array (
'EMAIL' => $email,
'FNAME' => $first_name,
'LNAME' => $last_name,
),
false,
false
)) {
drupal_set_message ( t('Thank you. From now you will receive our promo materials'));
} else {
// Get last watchdog mailchimp error
$query = db_select ( 'watchdog', 'w' );
$query -> fields ( 'w' );
$query -> condition ( 'w.type', 'mailchimp', '=' );
$query -> condition ( 'w.timestamp', time() - 10, '>' ); // check for message in last 10 seconds
$query -> condition ( 'w.message', 'An error occurred subscribing @email to list @list. "%message"', '=' );
$query -> orderBy ( 'w.timestamp', 'DESC' );
$query -> range ( 0, 1 );
$ans = $query -> execute();
if ( $wd = $ans -> fetchAssoc() ) {
$wd['variables'] = unserialize ( $wd['variables'] );
$message = $wd['variables']['%message'];
// Get only error message
if ( preg_match ( '#Internal\sServer\sError:(.+)$#si', $message, $m )) {
$message = $m[1];
}
drupal_set_message ( $message, 'error' );
} else {
drupal_set_message ( 'Error occurred while adding your email to subscribe list', 'error' );
}
}