Simple form to email example

Inspired by http://drupal.org/node/197092 I decided to write a short snippet to demo how to take a simple form field, validate it and send the field to an email address on submission.

Like the above post, this snippet just asks for an email address with a submit button. Validation just checks the email address syntax.

This is really meant as a "starting point", it's up to you, the reader, to add bells and whistles as required.

To use this snippet, create a new block. Cut'n'paste the code below and set the blocks input filter to "PHP". Then place the block somewhere to use it.

<?php
$send_form_to
= 'jdow@example.com'; // Change this!

function my_sign_up_form() {
 
$form['email'] = array(
   
'#type' => 'textfield',
   
'#title' => '',
   
'#size' => '20',
  );
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => 'Subscribe',
  );
  return
$form;
}

function
my_sign_up_form_validate($form_id, $form) {
  if (!
valid_email_address($form['email'])) {
   
form_set_error('email', 'Your email address appears malformed');
  }
}

function
my_sign_up_form_submit($form_id, $form) {
 
$message = 'New signup email address: '. $form['email']; // Body of your email here.
 
drupal_mail('my_sign_up_form', $send_form_to, 'New signup', $message, variable_get('site_mail', 'an@example.com'));
 
drupal_set_message('Thank you for signing up to our email alerts'); // Your thank you message here
}

return
drupal_get_form('my_sign_up_form');
?>

btw, the above is a basic starting point and does not include any filtering so you are advised to see the handbook section on writing secure code

Thank you for writing this

PRZ - July 24, 2008 - 13:49

Thank you for writing this snippet.

I could not get it to function in a block on my 5.9 installation as written. I simplified it by removing variables the following way and it works like a charm:

<?php
function my_sign_up_form() {
 
$form['email'] = array(
   
'#type' => 'textfield',
   
'#title' => '',
   
'#size' => '20',
  );
 
$form['submit'] = array(
   
'#type' => 'submit',
   
'#value' => 'Subscribe',
  );
  return
$form;
}

function
my_sign_up_form_validate($form_id, $form) {
  if (!
valid_email_address($form['email'])) {
   
form_set_error('email', 'Your email address appears malformed');
  }
}

function
my_sign_up_form_submit($form_id, $form) {
 
$message = 'New Email List address: '. $form['email'];
 
drupal_mail('my_sign_up_form', 'an@example.com', 'New Email List Signup', $message, 'email_list@example.com');
 
drupal_set_message('Thank you for signing up to our email list!');
}

return
drupal_get_form('my_sign_up_form');
?>

Not sure why the variables were giving me troubles....

 
 

Drupal is a registered trademark of Dries Buytaert.