I have a custom "Like" widget and i allow users to delete their votes when clicking on it for a second time. What i want is after a user votes and the number of "Likes" increases to change the label to "Unlike" and after the user deletes the vote to revert the label back to "Like".

Is it possible somehow?

Comments

plessas’s picture

Well, it was easier than i thought. I used the hook_rate_widget_alter() function to alter the widget label when the user has voted for this entity. What I didn't expect was that the widget seems to reload after the user casts or deletes a vote, so there is no need for any other action (e.g. ajax). After the user clicks on it, it takes the right label.

function mymodule_rate_widget_alter(&$widget, $context) {
  //in my case i only have like-type widget for comments
  //so I only care about comments
  if($context['content_type'] == 'comment') {
    global $user;

    //check if current user has already liked this comment    
    $count = db_query('SELECT vote_id FROM votingapi_vote WHERE entity_type=\'comment\' AND entity_id=:eid AND uid=:uid', array(':eid'=>$context['content_id'],':uid'=>$user->uid))->rowCount();

    if($count != 0)    
      $widget->options[0][1] = t('Unlike');
  }
}
plessas’s picture

Status: Active » Closed (fixed)