Drupal 7: Printing Personal Contact Forms

Drupal 7: Printing Personal Contact Forms

Printing personal contact forms

With Drupal 7, it is pretty simple to add forms anywhere you can call PHP code using drupal_get_form(). Getting a personal contact form to print, however, is a bit more complicated. And not well documented. drupal_get_form() tells us a unique form instructor requires an object is passed as an argument, but does not really say how. Examining drupal_get_form(), one will notice function_get_args() is called.

function drupal_get_form($form_id) {
  $form_state = array();
  $args = func_get_args();

  // Remove $form_id from the arguments.
  array_shift($args);
  $form_state['build_info']['args'] = $args;
 
  return drupal_build_form($form_id, $form_state);
}

Now let's visit a user's contact page. To make things easier, I use the devel module to "pretty print" variables during development. This isn't required, you could replace dpm() with print_r(). In a module's *.module file, or a theme's template.php file, enter the following code.

/**
 * Implements hook_form_alter().
 */
function hook_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_state);
}

When you reload the user's personal contact page, the $form_state associative array will be printed. Locate $form_state['build_info']['args'] and you'll see the user object. These are the arguments drupal_get_form() will need in order to get the correct user's contact form. So now it's time to render this form somewhere else on the site. Wherever you want to render this form, the steps will be the same. I have successfully done this in a view, block, node, template files, and theme/module functions, although you will need the PHP filter module enabled and configured correctly for all but template files and theme/module functions. Views will also require the Views PHP module. Whichever is the case, use the following code (in a view, enter this into the "Output code" of a Views PHP field):

$account = user_load($uid);
 
$contact_pages = drupal_get_path('module', 'contact') . '/contact.pages';
module_load_include('inc', $contact_pages);
$form = drupal_get_form('contact_personal_form', $account);
 
print drupal_render($form);

That's it, you can now print a user's personal contact form anywhere on the site. I recently used this when creating a staff bio page for a client. I created a view that loaded user objects from a specific role, then used the above code to print each user's contact form below their bios.

Comments (0)


Add new comment

The content of this field is kept private and will not be shown publicly.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.