You are here

function choices_field_formatter_view in Poll Improved 7

Implements hook_field_formatter_view().

File

modules/choices/choices.module, line 70
Defines simple choices field.

Code

function choices_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $entity_id = $entity
    ->internalIdentifier();
  switch ($display['type']) {
    case 'choices_default':
    case 'choices_with_vote_count':
      $votes_total_count = db_query("SELECT COUNT(*) FROM {pollim_vote} WHERE pollim_id = :pid", array(
        ':pid' => $entity
          ->internalIdentifier(),
      ))
        ->fetchField();
      $choice_items = array();
      foreach ($items as $delta => $item) {
        $item_vote_count = db_query("SELECT COUNT(*) FROM {pollim_vote} WHERE pollim_id = :pid AND data = :data", array(
          ':pid' => $entity
            ->internalIdentifier(),
          ':data' => $delta,
        ))
          ->fetchField();

        //@todo: theme functions for the output
        $percentage = $votes_total_count ? round($item_vote_count * 100 / $votes_total_count) : 0;
        $votes_txt = $percentage . '%';
        $val = theme('choices_radiobtn', array(
          'element' => array(
            '#entity_id' => $entity_id,
            '#delta' => $delta,
            '#votes_count' => $votes_txt,
            '#txt' => $item['value'],
          ),
        ));
        $choice_items[$delta] = array(
          '#markup' => $val,
          '#percentage' => $percentage,
        );
      }
      $element[0] = array(
        '#choice_items' => $choice_items,
        '#total_count' => $votes_total_count,
        '#theme' => 'choices_choices',
      );
      break;
    case 'choices_plain':
      foreach ($items as $delta => $item) {
        foreach ($items as $delta => $item) {
          $val = theme('choices_radiobtn', array(
            'element' => array(
              '#entity_id' => $entity_id,
              '#delta' => $delta,
              '#txt' => $item['value'],
            ),
          ));
          $choice_items[$delta] = array(
            '#markup' => $val,
          );
        }
        $element[0] = array(
          '#choice_items' => $choice_items,
          '#theme' => 'choices_choices',
        );
      }
      break;
  }
  return $element;
}