background image
HomeRecent PostsDrupalSearchTagsRSSContactAboutAccount
Eric.London's picture

Unfortunately, the stock Drupal contact module does not satisfy everyone's functional requirements. I decided to weigh alternative solutions, but since all I wanted to do was add an additional field to the form and email, I decided to add a few lines of module code instead. This solution consists of adding a form_alter hook to modify the contact form and submit handler, and an additional submit handler function:

<?php
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
 
// check for contact form
 
if ($form_id == 'contact_mail_page') {
       
   
// prefix another submit handler
   
array_unshift($form['#submit'], '_MYMODULE_mail_page_submit');
       
   
// NOTE: since I want to insert the form element at a certain point,
    // I have to create a new $form object
   
$newForm = array();
       
   
// define insertion point
   
$ip = 'message';
       
   
// lop through $form object and duplicate the values
   
foreach ($form as $k => $v) {
           
     
// check for insertion point and add new form element
     
if ($k == $ip) {
       
// add phone number
       
$newForm['phone'] = array(
         
'#type' => 'textfield',
         
'#required' => true,
         
'#title' => 'Phone',
        );
      }
           
     
$newForm[$k] = $v;
    }
       
   
// replace $form object with new form
   
$form = $newForm;

  }
}

function
_MYMODULE_mail_page_submit($form, &$form_state) {   

 
// Since message is required by default,
  // I can concatenate the new form field onto the message variable
 
if (!empty($form_state['values']['phone'])) {
   
$form_state['values']['message'] .= "\n\nPhone: " . $form_state['values']['phone'];
  }
   
}
?>

Now, if I browse to the contact form, there is a new field (phone number in this example) inserted right above the message textarea. When I submit the form, the email sent contains the phone number as well.

Syndicate content