You are here

function _advpoll_insert_choices in Advanced Poll 6.3

Same name and namespace in other branches
  1. 5 advpoll.module \_advpoll_insert_choices()
  2. 6 advpoll.module \_advpoll_insert_choices()
  3. 6.2 advpoll.module \_advpoll_insert_choices()

Insert/update the choices for a poll.

Note: we pass choice data via _POST to allow for dynamic addition of choices. Drupal 6 AHAH support will let us switch to a clean implementation.

2 calls to _advpoll_insert_choices()
advpoll_insert in ./advpoll.module
Implementation of hook_insert().
advpoll_update in ./advpoll.module
Implementation of hook_update().

File

./advpoll.module, line 1182
Advanced Poll - a sophisticated polling module for voting, elections, and group decision-making.

Code

function _advpoll_insert_choices($node) {
  $nid = $node->nid;
  $weight = 0;
  $seen_ids = array();
  foreach ($node->choice as $index => $choice) {
    if ($choice['label'] != '') {

      // Mark this choice id as being seen.
      $choice_exist = db_result(db_query("SELECT COUNT(cid) FROM {advpoll_choices} WHERE nid = %d AND cid = %d", $nid, $index));
      if (!$choice_exist) {
        db_query("INSERT INTO {advpoll_choices} (nid, label, weight) VALUES (%d, '%s', %d)", $nid, $choice['label'], $weight);
        $seen_id = db_last_insert_id('advpoll_choices', 'cid');
      }
      else {
        db_query("UPDATE {advpoll_choices} SET label = '%s', weight = %d WHERE cid = %d", $choice['label'], $weight, $index);
        $seen_id = $index;
      }
      $seen_ids[$seen_id] = 1;
      $weight++;
    }
  }
  $all_ids_query = db_query("SELECT cid, label FROM {advpoll_choices} WHERE nid = %d", $nid);
  $all_ids = array();
  while ($row = db_fetch_array($all_ids_query)) {
    $all_ids[$row['cid']] = array(
      'label' => $row['label'],
    );
  }

  // Delete any choices that were removed (either dynamically or by submitting
  // a blank label).
  if (isset($node->choice)) {
    foreach ($all_ids as $id => $choice) {
      if (!isset($seen_ids[$id])) {
        db_query('DELETE FROM {advpoll_choices} WHERE cid = %d', $id);
        drupal_set_message(t('Deleted choice %label', array(
          '%label' => $choice['label'],
        )), 'status');

        // We could potentially also delete any votes for this choice, but let's
        // leave them in the database so that one can go back and check if anyone
        // voted for a deleted choice.
      }
    }
  }
}