Drupal 7 – Render the Privatemsg send message form programmatically

Privatemsg allows Drupal users sending message to each other. It is a must-have feature of community oriented websites. The module includes all necessary features including inbox, outbox, user block list etc. In my case, i want to render the send message form on the user profile page. So i created a block which generate the send message form by PHP code and attached it to the user profile page. Here you are.

<?php
  // Load the module
  module_load_include('pages.inc','privatemsg');

  // We could get the user id from arg(1) becoz this block is shown in profile page.
  $recipients = array(user_load(arg(1)));
  $subject = 'Hello ' . $recipients[0]->name;
  print drupal_render(drupal_get_form('privatemsg_new', arg(1), $subject));

  // Restore the page title
  drupal_set_title($recipients[0]->name);
?>

 

Please note that drupal_get_form() returns a render array in Drupal 7, you need to use drupal_render() to convert it to a string that you can print. And i also need to reset the title to username becoz the privatemsg_new form will override the page title.

Done =)

Reference:

4 thoughts on “Drupal 7 – Render the Privatemsg send message form programmatically”

    1. you can try to refresh the content by ajax in regular interval, but probably that will overwhelm the server as there would be many requests.

      Currently, there is no mature module for IM in Drupal. Maybe you could consider the following 3rd party codes.
      IntraMessenger

      Like

    1. Oh, sorry, i just forgot include module in my code…
      So that’s the way:

      global $user;
      module_load_include('pages.inc', 'privatemsg');
      $account = user_load($user-&gt;uid);
      $build[] = drupal_get_form('privatemsg_list', 'list', $account); // it's in hook_view_alter
      

      Like

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.