Blog

How to Add a Field to the Drupal Contact form

Written by Joaquin Lippincott, CEO | Jan 27, 2009 12:00:00 AM
Filed under:

Ever wish you could use the existing Drupal Contact module as your sitewide contact form and just add a field or two? You can and it's really easy. All you need to do is create a new module and add the fields via the hook_form_alter() function. Here's an example of how we do it on metaltoad.com:

<?php	
 
/**
 * Implementation of hook_form_alter().
 * @see http://api.drupal.org/api/function/hook_form_alter
 * We add a few custom fields to the default Drupal contact form
 */
function mtmcontact_form_contact_mail_page_alter(&$form, $form_state) {
 
	$form['company'] = array(
		'#title' => t('Your company'),
		'#type' => 'textfield',
		'#required' => true,
	);
	$form['phone'] = array(
		'#title' => t('Your phone'),
		'#type' => 'textfield',
	);
 
	// reorder the elements in the form to include the elements being inserted
	$order = array('contact_information', 'name', 'company', 'phone', 'mail', 'subject', 'message', 'copy', 'submit');
	foreach($order as $key => $field) {
		$form[$field]['#weight'] = $key;
	}
}

The second part keeps the fields in an explicit order and includes references to the form elements that are already created by the Contact module. To change the order, simply modify the array.

Want more awesome content like this? Check out our top 20 Drupal tips of all time!