Send mail on form submit Drupal 7 token support

If you are going to send mail on form submit you should use simple hook_form_alter. You are able to use it in current theme template.php but it would be much easier to use custom module. in case if you are using this code in your theme template.php you should change 'yourmodule_' on 'yourtheme_'  name.

function yourmodule_form_alter(&$form, $form_state, $form_id) {
	if($form_id == 'your_form_id') {
		$form['#submit'][] = 'yourmodule_submit_webform_action';

To add custom submit function we add new element into array:

$form['#submit'][] = 'yourmodule_submit_webform_action';

'yourmodule_webform_mail_submit_webform_action' name of our custom function. You should notice that we added new element. We do not have to remove existing $form['#submit'] elements because it leads to problems.

So lets describe our custom submit function:

function yourmodule_submit_webform_action (&$form, &$form_state) {
	$form_content = $form_state['values']['submitted_tree'];
	$name = $form_content['name'];
	 global $user;

In above function we get submitted fields we need from array $form_state['values']['submitted_tree']. In this case this is 'name' and 'mail'. Then we prepeare parameters to pass them to yourmodule_webform_mail_send_mail function. 

Here are our function wich prepears our mail before sending (replace tokens) yourmodule_webform_mail_send_mail:

function yourmodule_send_mail($to, $from, $subject, $body, $user) {
	$params = array(
				'subject' => $subject,
				'body' => array(token_replace($body, array('user'=>$user), array('callback' => 'user_mail_tokens', 'sanitize' => FALSE)),
			drupal_mail('yourmodule', 'information', $to, language_default(), $params, $from);

So finally we discuss function wich actually sen dour mail:

function  yourmodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'information':
      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];

Thats all, check our blog for updates and new articles, contact us if you need to ask some questions, our team are always open to any requests. in later articles i'll tell you how to create user programmatically after form submit. 

10 out of 10 based on 1 ratings.