You are here

function advpoll_merge_writein_form_submit in Advanced Poll 7

Same name and namespace in other branches
  1. 7.3 includes/advpoll.pages.inc \advpoll_merge_writein_form_submit()
  2. 7.2 includes/advpoll.pages.inc \advpoll_merge_writein_form_submit()

File

includes/advpoll.pages.inc, line 507

Code

function advpoll_merge_writein_form_submit($form, &$form_state) {
  $lang = $form_state['build_info']['args'][0]->language;
  $mergeFrom = strtolower($form['merge_writein']['choices']['#value']);
  $mergeTo = strtolower($form['merge_writein']['all_choices']['#value']);
  $nid = $form_state['build_info']['args'][0]->nid;
  $choices = $form_state['build_info']['args'][0]->advpoll_choice[$lang];
  $fromTag = '';
  $toTag = '';

  // match up unique choice id with selected choice
  foreach ($choices as $choice) {
    if (strtolower(strip_tags($choice['choice'])) == $mergeFrom) {
      $fromTag = $choice['choice_id'];
    }
    else {
      if (strtolower(strip_tags($choice['choice'])) == $mergeTo) {
        $toTag = $choice['choice_id'];
      }
    }
  }

  // no matches, no merge
  if (!$fromTag || !$toTag) {
    drupal_set_message(t('Unidentifed index for index merging.'));
    return;
  }

  // get votes that belonged to the merge from value
  $criteria = array(
    'entity_id' => $nid,
    'tag' => $fromTag,
  );
  $mergeFromVotes = votingapi_select_votes($criteria);

  // transfer merge from votes to new vote object and update votingapi
  foreach ($mergeFromVotes as $vote) {
    $votes = array(
      'entity_type' => 'advpoll',
      'entity_id' => $nid,
      'value' => $vote['value'],
      'tag' => $toTag,
      'uid' => $vote['uid'],
      'vote_source' => $vote['vote_source'],
    );
    votingapi_set_votes($votes);
  }

  // remove votes for merge from tag
  votingapi_delete_votes($mergeFromVotes);

  // remove choice from node.
  $node = node_load($nid);
  if ($node) {
    $nodeChoices = $node->advpoll_choice[$node->language];
    $updatedChoices = array();
    foreach ($nodeChoices as $item) {
      $id = $item['choice_id'];
      if ($id != $fromTag) {
        $updatedChoices[] = $item;
      }
    }
    $node->advpoll_choice[$node->language] = $updatedChoices;
    node_save($node);
  }
}