Sending webform submissions to email based on value of field
We recently did a site for a client that allowed patients to submit a webform to request an appointment. The user could choose their physician and based on their choice, the submission would be emailed to the chosen doctor’s secretary. I originally thought about using the key part of the key|value pair for the select list to store the secretary’s email address, with the doctor’s name. This wouldn’t work, however, because the key could not contain standard email address characters. The solution involved isn’t exactly dynamic, but for a select list that won’t change much (the case here), it’s a fairly elegant solution. Here is the select list and associated code. I created this with the webform UI using a simple select list webform field.
Next, is a screenshot of the webform “email settings.” (click for a larger view):
Basically, I’ve added a line to the bottom of every email that contains a specific string followed by the doctor chosen. Because the string will look the same every time, we are then able to use regular expressions to get the chosen doctor. Using hook_mail_alter, we can then modify the email ‘to’ address based on the doctor chosen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
/** * Implementation of hook_mail_alter(). */ function mymodule_mail_alter(&$message) { if ($message['id'] == 'webform_submission' && $message['params']['node']->nid == 63) { $message['to'] = mymodule_process_appt_recipient($message); } } /** * Process appointment recipient * * @param $message * Message array from webform * @return * An email address */ function mymodule_process_appt_recipient($message) { $pattern = '/reqdoc:(.*)/'; preg_match($pattern, $message['body'][0], $matches); if ($matches[1]) { switch ($matches[1]) { case 'Dr. Agile': $recip = '<a href="mailto:myemail_0@gmail.com">myemail_0@gmail.com</a>'; break; case 'Dr. Adam': $recip = '<a href="mailto:myemail_1@gmail.com">myemail_1@gmail.com</a>'; break; case 'Dr. Keystroke': $recip = '<a href="mailto:myemail_2@gmail.com">myemail_2@gmail.com</a>'; break; default: $recip = $message['to']; } return $recip; } else { // couldn't find email recipient, send to default 'to' address // defined in webform email settings return $message['to']; } } |