Customize Drupal Contact Form

Step 1: You need an empty module

As explained here, you need a place to put your custom code. A good place for your “code tricks” can be an empty module where you put all your custom stuff. You can go here for more info on creating an empty module.
Step 2: Modify the form

For example, imagine you want to add a selector field to your site-wide contact form. For example, you want to ask user’s favourite color. This would be the code:

function [--foo--]_form_contact_mail_page_alter(&$form, $form_state) {
// Options on our new selector box
$options = array(
‘red’ => t(‘Red’),
‘green’ => t(‘Green’),
‘blue’ => t(‘Blue’),
‘none’ => t(‘I don\’t bother’)
);
$form['color'] = array(
‘#title’ => t(‘Favourite color’),
‘#type’ => ‘select’,
‘#required’ => true,
‘#options’ => $options,
‘#default_value’ => ‘none’
);

// Resorting the whole form, so that our new field appears where we want to.
$order = array (‘name’, ‘mail’, ‘subject’,
‘color’, ‘cid’, ‘message’, ‘copy’, ‘submit’);
foreach($order as $key => $field) {
$form[$field]['#weight'] = $key;
}
}

That’s it, we modified the form. Remember to change [--foo--] by your custom module’s name, and please notice we use the t() function to make the text of the new field translatable.

If you want more info on forms manipulation, check the Drupal Forms API quickstart guide.

Now, we must modify the output so we receive the data of this new field when someone sends us a message.
Step 3: Modify the email we receive

This is even easier. We use the mail_alter hook, being careful to alter only the contact form mail, as this hook is used for every mail the system sends:

function [--foo--]_mail_alter(&$message) {
// We have to be careful to alter only the contact form mail,
// as this hook is used for every mail the system sends.
if ($message['id'] == ‘contact_page_mail’) {
// We’re gonna insert ‘Favourite color’ before message body.
$message['body'][2] = $message['body'][1];
$options = array(
‘red’ => t(‘Red’),
‘green’ => t(‘Green’),
‘blue’ => t(‘Blue’),
‘none’ => t(‘I don\’t bother’)
);
$message['body'][1] = t(‘Favour’).’: ‘
.$options[$message['params']['color']];
}
}

Save and enjoy. You did it. You modified the site-wide contact form in Drupal. No big deal, isn’t it?

Advertisement
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s