You are here

function advpoll_form_poll_edit_form_validate in Advanced Poll 8

Cleaner for the poll_edit_form.

1 string reference to 'advpoll_form_poll_edit_form_validate'
advpoll_form_poll_edit_form_alter in ./advpoll.module
Implements hook_form_FORM_ID_alter().

File

./advpoll.module, line 115

Code

function advpoll_form_poll_edit_form_validate(&$form, FormStateInterface $form_state) {
  $number_votes = $form_state
    ->getValue('field_number_of_votes');
  if ($number_votes && !empty($number_votes[0]['value'])) {
    $poll_type = $form_state
      ->getValue('field_poll_type');
    if (empty($poll_type)) {

      // For the single poll, set max number to 1.
      $form_state
        ->setValue('field_number_of_votes', [
        [
          'value' => 1,
        ],
      ]);
    }
    else {

      // Otherwise validate maximum.
      $choices = $form_state
        ->getValue('choice');
      if ($choices) {
        unset($choices['add_more']);
        $choices = array_filter($choices, function ($item) {
          return !empty($item['target_id']);
        });
        $choices_count = count($choices);
      }
      else {
        $choices_count = 0;
      }
      if ($number_votes[0]['value'] > $choices_count) {
        $form_state
          ->setErrorByName('field_number_of_votes', t('Max votes should be less than or equal of the choices count.'));
      }
    }
  }
}