0

How do I add fields to the standard Drupal contact form? Can this be done programmatically or is it a task for a module?

  • Maybe you should give webforms a go... – Alex Gill Nov 20 '12 at 10:51
  • pls see the updated answer. – AjitS Nov 21 '12 at 14:28
2

Yes, you can do that programmatically using the function hook_form_alter in a custom module. Follow this for creating a custom module.

function MODULE_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'contact_personal_form') {
    $form['new_field'] = array (
      '#title' => t('New field'),
      '#type' => 'textfield',
      'description' => t('The description of the new field goes here...'),
      '#required' => TRUE, // make the user to fill it compulsorily           
    );
  }
}

Update: I forgot to mention that, the above code will just add the field to the form. The field is not added the mail you send. You should implement hook_mail_alter and add the field to the body, by something like:

function MODULE_mail_alter(&$message) {
  if($message['id'] == 'contact_user_mail') {
    $message['body'][] = $message['params']['new_field'];  //value of key 'new_field' same as in $form['new_field'] above in form alter
  }
}
  • And the site wide contact form would be contact_site_form I guess. – Neograph734 Nov 20 '12 at 11:07
  • 1
    @Neograph734 - you can find out the $form_id of any form by printing it out in the hook_form_alter, in this case just add echo $form_id; before the if condition above. Note that the $form_id will be printed on the respective form. – AjitS Nov 20 '12 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.