You are here

public function RateWidgetBaseForm::buildForm in Rate 8.2

Form constructor.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

array The form structure.

Overrides EntityForm::buildForm

File

src/Form/RateWidgetBaseForm.php, line 137

Class

RateWidgetBaseForm
Form controller for rate vote forms.

Namespace

Drupal\rate\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildForm($form, $form_state);
  $entity = $this
    ->getEntity();
  $voted_entity_type = $entity
    ->getVotedEntityType();
  $voted_entity_id = $entity
    ->getVotedEntityId();
  $voted_entity = $this->entityTypeManager
    ->getStorage($voted_entity_type)
    ->load($voted_entity_id);
  $result_function = $this
    ->getResultFunction($form_state);
  $options = $form_state
    ->get('options');
  $option_classes = $form_state
    ->get('classes');
  $form_id = Html::getUniqueId('rate-widget-base-form');
  $plugin = $form_state
    ->get('plugin');
  $settings = $form_state
    ->get('settings');
  $voting = $settings
    ->get('voting');
  $display = $settings
    ->get('display');
  $results = $settings
    ->get('results');
  $template = $settings
    ->get('template');
  $rate_widget = $form_state
    ->get('rate_widget');
  $value_type = $entity
    ->get('value_type')->value;
  $form['#cache']['contexts'][] = 'user.permissions';
  $form['#cache']['contexts'][] = 'user.roles:authenticated';
  $form['#attributes']['id'] = $form_id;
  $rate_options = [];

  // Remove labels on all templates, except for options and labelled widgets.
  $labelled_widgets = [
    'yesno',
    'custom',
    'emotion',
  ];
  if ($value_type != 'option') {
    if (!in_array($template, $labelled_widgets)) {

      // Remove the labels.
      foreach ($options as $key => $value) {
        $rate_options[$key] = '';
      }
    }
    else {
      $rate_options = $options;
    }
  }
  else {

    // Options with labels.
    $rate_options = $options;
  }
  $form['value'] = [
    '#prefix' => '<div class="' . $template . '-rating-wrapper">',
    '#suffix' => '</div>',
    '#type' => 'radios',
    '#options' => $rate_options,
    '#default_value' => $entity
      ->isNew() ? NULL : (int) $entity
      ->getValue(),
    '#attributes' => [
      'class' => [
        $template . '-rating-input',
      ],
    ],
    '#theme_wrappers' => [],
    '#wrapped_label' => TRUE,
  ];
  $vote_type = $entity
    ->bundle();
  $votes = [];
  $user_id = $entity
    ->get('user_id')->target_id;
  if (isset($results['result_type'])) {
    if ($results['result_type'] == 'user_vote_empty' || $results['result_type'] == 'user_vote_average') {
      $votes = $plugin
        ->getVotes($form_state
        ->get('entity_type'), $form_state
        ->get('entity_bundle'), $form_state
        ->get('entity_id'), $vote_type, $value_type, $rate_widget, $user_id);
      if ($results['result_type'] == 'user_vote_average' && count($votes) == 0) {
        $votes = $plugin
          ->getVotes($form_state
          ->get('entity_type'), $form_state
          ->get('entity_bundle'), $form_state
          ->get('entity_id'), $vote_type, $value_type, $rate_widget);
      }
    }
    else {
      $votes = $plugin
        ->getVotes($form_state
        ->get('entity_type'), $form_state
        ->get('entity_bundle'), $form_state
        ->get('entity_id'), $vote_type, $value_type, $rate_widget);
    }
  }

  // Sum of all options for numberupdown.
  $all_votes = 0;
  $count_votes = 0;
  foreach ($votes as $vote) {
    $all_votes += array_sum($vote);
    $count_votes += count($vote);
  }

  // Save the results for each option separately and add classes.
  if (isset($template) && $template != 'fivestar') {
    $form['value']['#attributes']['class'][] = 'rating-input';
    foreach ($options as $key => $option) {
      $form['value'][$key]['#attributes']['twig-suggestion'] = 'rating-input';
      $form['value'][$key]['#attributes']['class'][] = 'rating-input';
      $form['value'][$key]['#attributes']['class'][] = $template . '-rating-input';

      // Set the option results.
      if (isset($results['result_type']) && $results['result_type'] != 'vote_hidden') {
        if ($template == 'numberupdown') {
          if ($key > 0) {
            $form['value'][$key]['#option_result'] = isset($all_votes) ? $all_votes : 0;
          }
        }
        else {

          // Use sum for points and count for option.
          if ($value_type == 'option') {
            $vote_sum[$key] = isset($votes[$key]) ? count($votes[$key]) : 0;
          }
          else {
            $vote_sum[$key] = isset($votes[$key]) ? array_sum($votes[$key]) : 0;
          }
          $form['value'][$key]['#option_result'] = $vote_sum[$key] < 0 ? $vote_sum[$key] * -1 : $vote_sum[$key];
        }
      }
      if (isset($option_classes[$key]) && $option_classes[$key] != NULL) {
        $form['value'][$key]['#label_attributes']['class'][] = 'rating-label';
        $form['value'][$key]['#label_attributes']['class'][] = 'rating-label-' . $template;
        $form['value'][$key]['#label_attributes']['class'][] = 'rating-label-' . $template . '-' . strtolower(Html::cleanCssIdentifier($option));
        $form['value'][$key]['#label_attributes']['class'][] = $option_classes[$key];
      }
      else {
        $form['value'][$key]['#label_attributes']['class'][] = 'rating-label';
        $form['value'][$key]['#label_attributes']['class'][] = $template . '-rating-label';
        $form['value'][$key]['#label_attributes']['class'][] = $template . '-rating-label-' . strtolower(Html::cleanCssIdentifier($option));
      }
    }
  }
  else {
    foreach ($options as $key => $option) {

      // Add attributes and classes to the inputs.
      $form['value'][$key]['#attributes']['twig-suggestion'] = 'rating-input';
      $form['value'][$key]['#attributes']['class'][] = 'rating-input';
      $form['value'][$key]['#attributes']['class'][] = $template . '-rating-input';
      $form['value'][$key]['#attributes']['class'][] = $template . '-rating-input-' . $key;

      // Add attributes and classes to the labels.
      $form['value'][$key]['#label_attributes']['class'][] = 'rating-label';
      $form['value'][$key]['#label_attributes']['class'][] = $template . '-rating-label';
      $form['value'][$key]['#label_attributes']['class'][] = $template . '-rating-label-' . $key;
      if (isset($option_classes[$key]) && $option_classes[$key] != NULL) {
        $form['value'][$key]['#label_attributes']['class'][] = $option_classes[$key];
      }
    }

    // Show the result after the last option.
    $entity_value = $entity
      ->getValue();
    if (isset($results['result_type']) && $results['result_type'] != 'vote_hidden') {
      if ($results['result_type'] == 'user_vote_empty') {
        $vote_avg = isset($entity_value) ? $entity_value : 0;
      }
      elseif ($results['result_type'] == 'user_vote_average') {
        $vote_avg = isset($entity_value) ? $entity_value : number_format($this
          ->getResults($result_function), 1);
      }
      elseif ($results['result_type'] == 'vote_average') {
        $vote_avg = number_format($this
          ->getResults($result_function), 1);
      }
      $form['value'][$key]['#option_result'] = $vote_avg;

      // Show the average value as stars.
      if ($entity
        ->isNew()) {
        if ($results['result_type'] == 'user_vote_average' || $results['result_type'] == 'vote_average') {
          foreach ($options as $option_id => $option) {
            if ($option_id <= $vote_avg) {
              $form['value'][$option_id]['#label_attributes']['class']['average'] = 'average';
            }
          }
        }
      }
    }
  }

  // Set 'rate-voted' html class to radio element.
  $form = $this
    ->setVotedClass($form, $entity, $options);

  // Set the rate widget to readonly, if the entity uses a vote deadline.
  $deadline_disabled = $this
    ->checkDeadlineDisabled($voted_entity, $voting);
  $form['value']['#deadline_disabled'] = $deadline_disabled === TRUE ? TRUE : FALSE;
  if (isset($display['readonly']) && $display['readonly'] === 1 || !$plugin
    ->canVote($entity) || $deadline_disabled === TRUE) {
    $form['value']['#disabled'] = TRUE;
    $form['value']['#prefix'] = '<div class="' . $template . '-rating-wrapper rate-disabled" can-edit="false">';
  }
  else {
    $form['value']['#disabled'] = FALSE;
    $form['value']['#prefix'] = '<div class="' . $template . '-rating-wrapper rate-enabled" can-edit="true">';
  }

  // Take care of the widget default value.
  if (!$entity
    ->isNew()) {
    if (!isset($results['result_type']) || $results['result_type'] == '0') {
      $form['value']['#default_value'] = $this
        ->getResults($result_function);
    }
    else {
      $form['value']['#default_value'] = (int) $entity
        ->getValue();
    }
  }

  // Get the results container.
  if (isset($results['result_position']) && $results['result_position'] !== 'hidden') {
    $form['result'] = [
      '#theme' => 'container',
      '#attributes' => [
        'class' => [
          'vote-result',
        ],
      ],
      '#children' => [],
      '#weight' => 100,
    ];
    $form['result']['#children']['result'] = $plugin
      ->getVoteSummary($entity);
    $form['result']['#children']['result']['#disabled'] = $form['value']['#disabled'];
    $form['result']['#children']['result']['#deadline_disabled'] = $deadline_disabled;
  }

  // The form submit button.
  $form['submit'] = $form['actions']['submit'];
  $form['actions']['#access'] = FALSE;
  $form['submit'] += [
    '#type' => 'button',
    '#attributes' => [
      'class' => [
        $template . '-rating-submit',
      ],
    ],
    '#ajax' => [
      'callback' => '::ajaxSubmit',
      'event' => 'click',
      'wrapper' => $form_id,
      'progress' => [
        'type' => NULL,
      ],
    ],
  ];

  // Base widget template. Can create additional twig templates.
  $form['#theme'] = 'rate_widget';
  $form['#rate_widget'] = $rate_widget;
  $form['#widget_template'] = $template;
  $form['#display_settings'] = $display;
  $form['#results_settings'] = $results;
  $form['#results'] = $plugin
    ->getVoteSummary($entity);
  $form['#results']['#disabled'] = $form['value']['#disabled'];
  $form['#results']['#deadline_disabled'] = $deadline_disabled;
  return $form;
}