Search code examples
drupaldrupal-7

does votingapi_set_votes handles voting and unvoting


does votingapi_set_votes handles voting and unvoting. I will try to use the same logic as this Drupal Creating Votes in Voting API Through Code to create a vote. What i am asking is how to handle voting and unvoting.


Solution

  • Generally you add votes using votingapi_set_votes and delete votes using votingapi_delete_votes.

    For both these functions you need a base criteria, something like this.

    $criteria = array(
      'entity_type' => 'node',
      'entity_id' => $node->nid,
      'uid' => $user->uid,
      'value_type' => 'points',
      'tag' => 'vote',
    );
    

    For setting vote you need its value, which usually differs from criteria only by value field.

    $votes = $copy_of_criteria;
    $votes['value'] = 666;
    

    Then votingapi_set_votes($votes, $criteria) will delete all votes matching $criteria, and then add new votes (specified by $votes). This function also takes care of recalculating votes cache (i.e. aggregated values).

    For deleting votes ("unvote") you firstly need to select required votes and then pass them into the votingapi_delete_votes function:

    $votes = votingapi_select_votes($criteria);
    votingapi_delete_votes($votes);
    

    This function does not recalculates voting cache, so you need to call votingapi_recalculate_results('node', $node->nid).