Commit 1c1bb6ed authored by Karl Yoder's avatar Karl Yoder
Browse files

Issue #3313514 by kyoder: widget validation improvements.

parent 1b0c2b93
Loading
Loading
Loading
Loading
+37 −0
Original line number Diff line number Diff line
@@ -2,6 +2,7 @@

namespace Drupal\entity_repeat\Plugin\Field\FieldWidget;

use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
@@ -33,6 +34,14 @@ class EntityRepeatWidget extends parentAlias {
      return $element;
    }

    // Remove infinite repeat option as it is not viable.
    unset($element['ends_mode']['#options']['infinite']);
    // Make date the default end option.
    $element['ends_mode']['#default_value'] = 'date';
    // Make date the first option.
    $element['ends_mode']['#options'] = ['date' => $element['ends_mode']['#options']['date']] + $element['ends_mode']['#options'];


    $element['entity_repeat_enabled'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Replicate this entity for each of the generated dates'),
@@ -82,6 +91,34 @@ class EntityRepeatWidget extends parentAlias {

    $entity = $form_state->getformObject()->getEntity();
    $entity->data['entity_repeat_enabled'] = 1;

    $start = $form_state->getValue(array_merge($element['#parents'], ['start']));
    $end = $form_state->getValue(array_merge($element['#parents'], ['end']));
    $mode = $form_state->getValue(array_merge($element['#parents'], ['mode']));
    $ends_mode = $form_state->getValue(array_merge($element['#parents'], ['ends_mode']));
    $ends_date = $form_state->getValue(array_merge($element['#parents'], ['ends_date']));
    $ends_count = $form_state->getValue(array_merge($element['#parents'], ['ends_count']));

    // Start and end dates must be provided.
    if (!$start instanceof DrupalDateTime) {
      $form_state->setError($element['start'], t('Start date must be provided.'));
    }
    if (!$end instanceof DrupalDateTime) {
      $form_state->setError($element['end'], t('End date must be provided.'));
    }

    // A limit to repeats must be provided if repeating more than once.
    if ($mode != 'once') {
      // Date must be provided if ends mode is date.
      if ($ends_mode == 'date' && !$ends_date instanceof DrupalDateTime) {
        $form_state->setError($element['ends_date'], t('Date to end repeats must be provided.'));
      }
      // Count must be provided if ends mode is count.
      if ($ends_mode == 'count' && empty($ends_count)) {
        $form_state->setError($element['ends_count'], t('Number of occurrences must be provided.'));
      }
    }

  }

}