During one of my project work there was requriement to display the comment form on the non-node page.

Here in this context non-node page means the page other than node/nid.

I was using plain drupal without panels and other module. If we are using panels then we can always put comment pane in the related page.

As I was using plain Drupal i wanted to render the form via template file aka tpl file.

We can't directly do on node tpl file becasue in tpl file $comment is not bound to nid.

So i followed the approch to create the variable that stores the form and render in the tpl file..

  1. Create any simple module and implement hook_node_view() 
    Here we are first mapping the $comment->nid to $node->nid 
    Then get the comment form using drupal_get_form() function.
    If you want to set the destination URL after form submission then you can set that as well in $form['#action']
    Add custom validation in case if you want to validate few more things than drupal's default validation function.
    Then assign our form to any variable. We will print this variable in node.tpl.php file.
    Write the following code in hook_node_view().

    /**
     * Implements hook_node_view().
     */
    function mymodule_node_view($node, $view_mode, $langcode) {
      if ($node->type == 'article') {
        $comment = new stdClass();
        $comment->nid = $node->nid;
        $form = drupal_get_form('comment_node_article_form', $comment);
        $url = 'node/' . $node->nid;
        //$form['#action'] = url($url);
        $form['#validate'][] = 'mymodule_comment_custom_form_validate'; // If you want to do custom validation for comment
        $node->custom_comment_form_article = $form;
        $node->custom_comment_form_article['#weight'] = 100;
      }
    }
     
  2. Now in template file you can render the variable which we created in our node view.
    You can create a separate tpl file for article with node--article.tpl.php file.
    You can render your form in template file using following snippet:

    <?php print render($custom_comment_form_article); ?>
     
Tags: 

Post new comment