0

I want to change email addresses based on postal codes entered by users. My code looks like below.

function my_webform_tracker_webform_submission_render_alter(&$renderable) {
  $node_id = (int)$renderable['#node']->nid;
  if ($node_id == 257) {
    $postal_code = (int)$renderable['#submission']->data[5][0];
    if($postal_code >= 14000 && $postal_code <= 14990) {
      $renderable['#email'][email] = "thisemailid@mydomain.com";
      $renderable['#node']->webform['emails'][1]['email'] = "thisemailid@mydomain.com";
      $renderable['#node']->webform['emails'][2]['email'] = "thisemailid@mydomain.com";
      //print "<pre>"; print_r($renderable); exit;
    }
  }
}

I tried a lot but the email id seems to be not changed. Please help me figure this out.

0
1

I think a more apt place to alter the destination email would be hook_mail_alter() where Drupal lets you alter an email before sending it out. The webform module includes all the submission data in the $message['params']['submission'] object.

You can do something like this in your module:

/**
 * Implements hook_mail_alter().
 */
function MYMODULE_mail_alter(&$message) {

  //Catch Webform submissions when we have a valid postal code
  if($message['id'] == 'webform_submission') {
    $postal_code_component = 5;
    if(isset($message['params']['submission']->data[$postal_code_component][0])) {
      $postal_code = (int) $message['params']['submission']->data[$postal_code_component][0];

      //Find right addressee to switch to
      if(0 <= $postal_code && $postal_code <= 13999 ) { 
        $message['to'] = 'addressee.1@example.com'; 
      } elseif(14000 <= $postal_code && $postal_code <= 14990) { //Etc...
        $message['to'] = 'addressee.2@example.com';
      } else { //Catchall
        $message['to'] = 'addressee.3@example.com';
      }
    }
  }
}
0

I figured it out, actually I was using wrong hook to do the task. The right on would be "hook_webform_submission_presave". So my code will look like,

    function my_webform_tracker_webform_submission_presave($node, &$submission) {
      $postal_code = (int)$renderable['#submission']->data[5][0];
      if($postal_code >= 14000 && $postal_code <= 14990) {
        $node->webform['emails'][1]['email'] = "thisemailid@mydomain.com";
        $node->webform['emails'][2]['email'] = "thisemailid@mydomain.com";      
      }
    }

Thank You everyone for help!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.