4

I need to prevent users from posting comments based on some conditions but I can't find any hooks I can implement.

For nodes we have hook_node_access() but apparently there is no hook_comment_access()

Any ideas on how I can implement this?

I have tried something like this but apparently it doesn't work:

function my_module_entity_info(&$entity_info) {
  $entity_info["comment"]["access callback"] = "my_module_comment_access_callback";
}

function my_module_comment_access_callback($op, $comment){
  // some custom logic and return false...
  //...
  return comment_access($op, $comment);
}

My form is a custom form, displayed on multiple pages. I would like to prevent access to the comment entity and not to the form or page.

2
+50

You can get code from Comment Permissions and Comment Access modules.

something like

function comment_perm_form_alter(&$form, $form_state, $form_id) {
  #comment_node_merci_reservation_form
  if ($form['#id'] == 'comment-form' and arg(0) == 'comment') {
    $types = variable_get('comment_perm_node_types', array());
    $form_id_types = array();
    if (is_array($types)) {
      foreach ($types as $type) {
        if ($form_id == 'comment_node_' . $type . '_form') {

          $nid = $form['nid']['#value'];
          if (! comment_perm_access($nid)) {
            // for comment reply pages, redirect back to the node
            if (arg(0) == 'comment' && arg(1) == 'reply' && is_numeric(arg(2))) {
              drupal_set_message(_comment_perm_access_denied_message($nid), 'error');
              drupal_goto('node/' . arg(2));
    }
  }

          if (arg(0) == 'comment' && arg(2) == 'edit' && is_numeric(arg(1))) {
            if (! comment_perm_edit_access($nid)) {
              drupal_set_message(_comment_perm_access_denied_message($nid), 'error');
              drupal_goto('node/' . $nid);
            }
          }
      }
  }
    }
  }

}

then you can add you own condition.

You can also use above module ,if it is fulfilling your requirement.

  • Not the answer I was looking for but maybe there is no other possibility to do this. I would like to prevent access to the comment entity and not to the form or page. – Marius Ilie Apr 11 '16 at 9:02
1

Good answer from @visabhishek, will try something similar, but more minimal:

function youmodule_form_alter(&$form, $form_state, $form_id) {
  // You can add more specific conditions here based on your reqs
  if ($form['#id'] == 'comment-form' && _your_conditions_callback() ) {        
      $form['#disabled'] = true;
      $form['#prefix'] = '<div class="messages warning"><h2>Not allowed</h2></div>';
  }
}

function _your_conditions_callback() {
  // Conditions block
  // return true;

  return false;
}

Maybe this helps as well, with lot less overhead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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