You are here

function advpoll_merge_writein_form_submit in Advanced Poll 7.2

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

File

includes/advpoll.pages.inc, line 537

Code

function advpoll_merge_writein_form_submit($form, &$form_state) {
  $lang = $form_state['build_info']['args'][0]->language;
  if (!isset($form_state['build_info']['args'][0]->advpoll_choice[$lang])) {
    $lang = 'und';
  }
  $merge_from = strtolower($form['merge_writein']['choices']['#value']);
  $merge_to = 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];
  $from_tag = '';
  $to_tag = '';

  // match up unique choice id with selected choice
  foreach ($choices as $choice) {
    if (strtolower(strip_tags($choice['choice'])) == $merge_from) {
      $from_tag = $choice['choice_id'];
    }
    elseif (strtolower(strip_tags($choice['choice'])) == $merge_to) {
      $to_tag = $choice['choice_id'];
    }
  }

  // no matches, no merge
  if (!$from_tag || !$to_tag) {
    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' => $from_tag,
  );
  $merge_fromVotes = votingapi_select_votes($criteria);

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

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

  // remove choice from node.
  $node = node_load($nid);
  if ($node) {
    $lang = $node->language;
    if (!isset($node->advpoll_choice[$node->language])) {
      $lang = 'und';
    }
    $node_choices = $node->advpoll_choice[$lang];
    $updated_choices = array();
    foreach ($node_choices as $item) {
      $id = $item['choice_id'];
      if ($id != $from_tag) {
        $updated_choices[] = $item;
      }
    }
    $node->advpoll_choice[$lang] = $updated_choices;
    node_save($node);
  }
}