2

I created a new user field to keep count of comments. I want to increase it by 1 after a user posts a comment and decrease it by 1 when comment is deleted.

Is there any way I can use rules to do this?

I know I can use views aggregation to get comment count, but I don't want to use this method.

1 Answer 1

1

It's worth noting the comment table has a 'uid' column so you could potentially query that to get the comment count for a user.

e.g:

$user_comment_count = db_select('comment', 'c')
->condition('uid', $account->uid)
->countQuery()
->execute()
->fetchField();

However, if you want to increment a field on comment insert, you could use Rules or hook_comment_insert

e.g: Rules export (Increment field_comment_count for current logged in user on comment insert)

{ "rules_increment_comment_count" : {
    "LABEL" : "increment_comment_count",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "site:current-user" ], "field" : "field_comment_count" } }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : { "input_1" : [ "site:current-user:field-comment-count" ], "op" : "+", "input_2" : "1" },
          "PROVIDE" : { "result" : { "result" : "Calculation result" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-comment-count" ],
          "value" : "[result:value]"
        }
      }
    ]
  }
}

You'll need to tweak the Rule to match your conf, but something like that should work.

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.