You are here

function PollViewForm::showPollResults in Poll 8

Display a themed poll results.

Parameters

\Drupal\poll\PollInterface $poll: The poll entity.

bool $block: (optional) TRUE if a poll should be displayed in a block. Defaults to FALSE.

Return value

array $output

1 call to PollViewForm::showPollResults()
PollViewForm::buildForm in src/Form/PollViewForm.php
Form constructor.

File

src/Form/PollViewForm.php, line 235

Class

PollViewForm
Displays banned IP addresses.

Namespace

Drupal\poll\Form

Code

function showPollResults(PollInterface $poll, $view_mode = 'default', $block = FALSE) {

  // Ensure that a page that shows poll results can not be cached.
  \Drupal::service('page_cache_kill_switch')
    ->trigger();
  $total_votes = 0;
  foreach ($poll
    ->getVotes() as $vote) {
    $total_votes += $vote;
  }
  $options = $poll
    ->getOptions();
  $poll_results = array();
  foreach ($poll
    ->getVotes() as $pid => $vote) {
    $percentage = round($vote * 100 / max($total_votes, 1));
    $display_votes = !$block ? ' (' . \Drupal::translation()
      ->formatPlural($vote, '1 vote', '@count votes') . ')' : '';
    $poll_results[] = array(
      '#theme' => 'poll_meter',
      '#choice' => $options[$pid],
      '#display_value' => t('@percentage%', array(
        '@percentage' => $percentage,
      )) . $display_votes,
      '#min' => 0,
      '#max' => $total_votes,
      '#value' => $vote,
      '#percentage' => $percentage,
      '#attributes' => array(
        'class' => array(
          'bar',
        ),
      ),
      '#poll' => $poll,
    );
  }

  /** @var \Drupal\poll\PollVoteStorageInterface $vote_storage */
  $vote_storage = \Drupal::service('poll_vote.storage');
  $user_vote = $vote_storage
    ->getUserVote($poll);
  $output = array(
    '#theme' => 'poll_results',
    '#raw_question' => $poll
      ->label(),
    '#results' => $poll_results,
    '#votes' => $total_votes,
    '#block' => $block,
    '#pid' => $poll
      ->id(),
    '#poll' => $poll,
    '#view_mode' => $view_mode,
    '#vote' => isset($user_vote['chid']) ? $user_vote['chid'] : NULL,
  );
  return $output;
}