You are here

public function ApprovalPollViewForm::buildForm in Advanced Poll 8

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 PollViewForm::buildForm

File

src/Form/ApprovalPollViewForm.php, line 40

Class

ApprovalPollViewForm
Class ApprovalPollViewForm

Namespace

Drupal\advpoll\Form

Code

public function buildForm(array $form, FormStateInterface $form_state, Request $request = NULL, $view_mode = 'full') {

  // Check start date.
  $startTimestamp = $this
    ->getStartTimestamp();
  if ($startTimestamp && $startTimestamp > time()) {

    // Start date is in the future.
    $date = \Drupal::service('date.formatter')
      ->format($startTimestamp, 'long');
    $form['start_date'] = [
      '#type' => 'markup',
      '#markup' => $this
        ->t('This poll will open on @date.', [
        '@date' => $date,
      ]),
    ];
    return $form;
  }

  // Get poll form with choice or results.
  $form = parent::buildForm($form, $form_state, $request, $view_mode);

  // Add poll-view-form class for AJAX selectors from the Poll module.
  $form['#attributes']['class'][] = 'poll-view-form';
  $form['#attributes']['class'][] = 'poll-view-form-' . $this->poll
    ->id();

  // If we render a form (not results), upgrade it.
  if (isset($form['choice'])) {
    $pollType = '';
    if ($this->poll
      ->hasField('field_poll_type')) {
      $pollType = $this->poll->field_poll_type->value;
    }

    // Change template.
    $form['#theme'] = 'poll_vote__advanced';

    // Upgrade for non-classic types.
    if ($pollType) {
      switch ($pollType) {
        case 'approval':

          // Set checkboxes.
          $form['choice']['#type'] = 'checkboxes';
          break;
      }
    }
    $isMultipleChoice = $form['choice']['#type'] == 'checkboxes';

    // Check write-in option.
    $isWriteInPoll = FALSE;
    if ($this->poll
      ->hasField('field_writein')) {
      $isWriteInPoll = $this->poll->field_writein->value;
    }
    if ($isWriteInPoll) {

      // Add special option and the text field.
      $form['choice']['#options'][self::writeInIndex] = $this
        ->t('Other (Write-in)');
      $writeInWrapperId = 'write-in-fieldset-wrapper-' . $this->poll
        ->id();
      $form['write_in'] = [
        '#type' => 'fieldset',
        '#prefix' => '<div id="' . $writeInWrapperId . '">',
        '#suffix' => '</div>',
      ];
      if ($isMultipleChoice) {
        $form['write_in']['#states']['visible']['input[name="choice[' . self::writeInIndex . ']"]']['checked'] = TRUE;
      }
      else {
        $form['write_in']['#states']['visible']['input[name="choice"]']['value'] = self::writeInIndex;
      }
      $maxChoices = $this
        ->getMaxChoices();

      // Gather the number of write-in in the form already.
      $numWriteIn = $form_state
        ->get('num_writein');

      // We have to ensure that there is at least one field.
      if ($numWriteIn === NULL) {
        $numWriteIn = 1;
        $form_state
          ->set('num_writein', $numWriteIn);
      }
      for ($i = 0; $i < $numWriteIn; $i++) {
        $form['write_in']['write_in_' . $i] = [
          '#type' => 'textfield',
        ];
      }

      // Check multiple write-in availability.
      $allowMultipleWriteIn = FALSE;
      if ($isMultipleChoice && $this->poll
        ->hasField('field_writein_multiple') && !$this->poll
        ->get('field_writein_multiple')
        ->isEmpty()) {
        $allowMultipleWriteIn = $this->poll
          ->get('field_writein_multiple')->value;
      }

      // Allow to add another write-in choice.
      if ($allowMultipleWriteIn && (empty($maxChoices) || $numWriteIn < $maxChoices)) {
        $form['write_in']['actions'] = [
          '#type' => 'actions',
        ];
        $form['write_in']['actions']['add'] = [
          '#type' => 'submit',
          '#value' => $this
            ->t('Add'),
          '#submit' => [
            '::addOneWriteIn',
          ],
          '#ajax' => [
            'callback' => '::addWriteInCallback',
            'wrapper' => $writeInWrapperId,
          ],
        ];
      }
    }

    // Hide write-in choices.
    if (!empty($form['choice']['#options'])) {
      $choiceKeys = array_keys($form['choice']['#options']);

      /** @var \Drupal\poll\PollChoiceInterface[] $choicesWriteIn */
      $choicesWriteIn = \Drupal::entityTypeManager()
        ->getStorage('poll_choice')
        ->loadByProperties([
        'id' => $choiceKeys,
        'field_writein' => TRUE,
      ]);
      if ($choicesWriteIn) {
        foreach ($choicesWriteIn as $choice) {
          unset($form['choice']['#options'][$choice
            ->id()]);
        }
      }
    }
  }
  return $form;
}