0

I have a content type where users can post reviews or comments. I want to achieve this with the comment module and not by creating another content type and using node reference.

So I want to limit the number of comment a user can post per node for a specific type of content type.

Again I also have other content types where I have given the users the option of commenting on article, and that can have multiple comments and replies.

Can anyone suggest me how to achieve this?

Can I do it through rules(I haven't tried yet)?

2 Answers 2

2

You could add a validate handler to the comment form

e.g, something like:

/**
 * hook_form_FORM_ID_alter
 */
function MODULE_form_comment_form_alter(&$form, &$form_state, &$form_id) {
  $form['#validate'][] = 'MODULE_comment_form_validate';
}

/**
 * Validate comment form submission
 */
function MODULE_comment_form_validate($form, &$form_state){
  $node = node_load($form_state['values']['nid']);
  if(isset($node->type) && $node->type = 'targetted_type'){
    $account = user_load_by_name($form_state['values']['name']);
    if(!empty($account->uid)){
      // Get comment count for this node type
      $query = db_select('comment', 'c');
      $query->join('node', 'n', 'n.nid = c.nid');
      $query->condition('c.uid', $account->uid);
      $query->condition('n.type', 'targetted_type');
      $query->countQuery();
      $comments = $query->execute()->fetchField();
      if($comments > variable_get('max_comments_targetted_type', 3)){
        form_set_error('name', 
          t('You are only allowed to post %max comments on this type of content.', array('%max' => variable_get('max_comments_targetted_type', 3))));
      }
    }
  }
}
1
  • In this case the problem is that the user can see the comment form and post it but comment will refused by validation function. I think this answer will be fine if complemented with wolverine answer: alter the node_view to unset the form if user can't post
    – sanzante
    Commented Jun 24, 2014 at 9:02
1

If you want to allow the user to comment only once then you can look into Onecomment module.

But if you want to use more complex logic then you can implement hook_node_view() and put your logic there and then unset the comment form from the $node->content. You can refer the code of Onecomment module.

2
  • In this case the problem is that a user could manage to send more post that allowed if, for example, oad several pages with the comment form. This can be fixed adding a custom validation function as David Thomas says in his answer.
    – sanzante
    Commented Jun 24, 2014 at 9:03
  • That logic is already there in Onecomment module, if you are writing custom module then you have to do that as well.
    – msmani
    Commented Jun 24, 2014 at 9:08

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.