3

I would like to set a given node's comment flag to 1 or 2 (to either show or hide the comment form) via my custom module, depending on certain conditions.

I have tried using hook_node_view, but this approach seems not to have worked:

function custom_node_view($node, $view_mode, $langcode) {
  $node->comment = 1;
}

Even if I explicitly set the comment flag to 1, it will remain 2 for a given node. If I dpm($node); just after setting the flag, the correct value will show in the devel information, but the comment form will still show...

According to comment.module, the values are such:

/**
 * Comments for this node are closed.
 */
define('COMMENT_NODE_CLOSED', 1);

/**
 * Comments for this node are open.
 */
define('COMMENT_NODE_OPEN', 2);

Is there a different hook I should be using to show/hide the comment form programmatically?

1 Answer 1

4

It looks like I can set the comment display correctly within hook_node_load(). I guess that runs a bit earlier in the process, and tells comment.module to not display the form for a given node.

Here's an example of what I ended up implementing:

<?php
/**
 * Implements hook_node_load().
 */
function custom_node_load($nodes, $types) {
  foreach ($nodes as $node) {
    $node->comment = COMMENT_NODE_CLOSED; // to close comments
  }
}
?>
5
  • 2
    comment.module adds the comments in comment_node_view(). So I guess you just need to make sure that your module runs before comment.module (set a lower weight) and then doing it in hook_node_view() should work fine. Note that it is possible that the updated flag value will be persisted to the database if someone node_save()'s it (Due to the static cache, all node_load() calls will share the same instance on a single site). Make sure that is not a problem.
    – Berdir
    Jun 1, 2011 at 23:45
  • 2
    And you could also use hook_entity_prepare_view(), then you don't need to mess with module weights: api.drupal.org/api/drupal/includes--common.inc/function/…
    – Berdir
    Jun 1, 2011 at 23:47
  • @Berdir That should be an answer.
    – apaderno
    Jun 2, 2011 at 12:39
  • Hmm... I really need to read up on hook_entity_ more. I'm still set in my Drupal 6 ways (meaning I have blinders on to many new D7 hooks). Jun 2, 2011 at 23:08
  • Has anyone checked if this disabling works on nodes that has NO comments attached with it? Doesnt work for me for some reason... Moreover, using the above solution apparently executes on the edit page also. So even if the node has open comment status, in the node edit form it will show closed and if user saves the node, it will save the comment status accidentally. Jan 18, 2018 at 7:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.