[Drupal] How to wrap the comments in a collapsible fieldset?

| | 2 min read

Comment module in Drupal makes it possible for users to comment on the nodes we create. And also the users get a chance to discuss on the topic as well. In this article I try to demonstrate how the comments for a node can be wrapped inside a fieldset. Isn't it a good choice? If you haven't done it, now will be a good time to do so.

Place the below function in our template.php.


/**
* Wraps comments in a collapsible fieldset.
*/
function YOUR_THEME_preprocess_comment_wrapper(&$variables) {
  // Provide contextual information.
  $variables['node'] = $variables['content']['#node'];
  $variables['display_mode'] = variable_get('comment_default_mode_' . $variables['node']->type, COMMENT_MODE_THREADED);
  // The comment form is optional and may not exist.
  $variables['content'] += array('comment_form' => array());
  $commentslist = $variables['content']['comments'];
  $variables['content']['comments'] = array(
    '#type' => 'fieldset',
    '#title' => format_plural($variables['node']->comment_count, '1 comment', '@count comments'),
    '#weight' => 0,
    //'#collapsible' => TRUE, // does not work and thus is not necessary
    //'#collapsed' => TRUE, // does not work and thus is not necessary
    '#pre_render' => array(),
    '#attributes' => array(),
  );
  // Make it manually collapsible as we cannot use #collapsible without the
  // FAPI element processor.
  $variables['content']['comments']['#attached']['library'][] = array('system', 'drupal.collapse');
  $variables['content']['comments']['#attributes']['class'][] = 'collapsible';
  $variables['content']['comments']['#attributes']['class'][] = 'collapsed';
  $variables['content']['comments']['commentslist'] = $commentslist;
}

Above is the function to wrap the comment form. Let's go a bit deeper.

Here we are collecting the the view mode of our comment form to the variable 'display_mode'.The comment form is made collapsible by setting the property type to 'fieldset', and finally the library and css are attached.

That is it, now you can have your comments in a collapsible fieldset.