Drupal: Attach a site-wide contact form to a page or block

As far as website contact forms go, Drupal's core Contact module provides pretty much everything it should right out of the box. But what if you want to add more information to the page (mailing address, for example), or position the form as a block, say, in a sidebar? In the first case, you would have the form automatically load inside another page node (such as we've done with our own Contact us page). In the second, you could create an empty block and attach the contact form to it. Here's how:

Attach a site-wide contact form to a node

Drupal 7.x:

  1. Open template.php in your theme folder and add the following code. Replace [THEME NAME] with the name of your theme. Replace the value of $nid with the actual ID of your node.

    /**
     * Implements preprocess_node().
     */
    function [THEME NAME]_preprocess_node(&$vars) {
      // Print contact form on contact page.
      $nid = 7;
      if ($vars['node']->nid == $nid && module_exists('contact')) {
        module_load_include('inc', 'contact', 'contact.pages');
        $contact_form = drupal_get_form('contact_site_form');
        // We need to manually prepare our status messages. (Thanks, Rémy!)
        $contact_form['#prefix'] = theme('status_messages');
        $vars['contact_form'] = render($contact_form);
      }
    }
  2. Open node.tpl.php in your theme folder (if you don't have it, copy it from your base theme or from modules/node). Add the following code to the spot where you would like the contact form to appear.

    if (!empty($contact_form)) {
      print $contact_form;
    }
  3. Clear all caches.

Attach a site-wide contact form to a block

Drupal 7.x:

  1. Open template.php in your theme folder and add the following code. Replace [THEME NAME] with the name of your theme. Replace the value of $module and $delta with the actual string values.

    Hint: To locate these values go to admin/structure/block and click on the "configure" link next to the block you want to print. The strings will be shown in the URL as such: admin/structure/block/manage/[module]/[delta]/configure.

    /**
     * Implements preprocess_block().
     */
    function [THEME NAME]_preprocess_block(&$vars) {
      // Preprocess the Contact form block. 
      $module = 'block';
      $delta = 3;
      if ($vars['block']->module == $module && $vars['block']->delta == $delta) {
        module_load_include('inc', 'contact', 'contact.pages');
        $contact_form = drupal_get_form('contact_site_form');
        // Manually prepare status messages.
        $contact_form['#prefix'] = theme('status_messages');
        $vars['content'] = render($contact_form);
      }
    }
  2. Clear all caches.