You are here

public function ScheduleEmailWebformHandler::buildConfigurationForm in Webform 6.x

Same name and namespace in other branches
  1. 8.5 modules/webform_scheduled_email/src/Plugin/WebformHandler/ScheduleEmailWebformHandler.php \Drupal\webform_scheduled_email\Plugin\WebformHandler\ScheduleEmailWebformHandler::buildConfigurationForm()

Form constructor.

Plugin forms are embedded in other forms. In order to know where the plugin form is located in the parent form, #parents and #array_parents must be known, but these are not available during the initial build phase. In order to have these properties available when building the plugin form's elements, let this method return a form element that has a #process callback and build the rest of the form in the callback. By the time the callback is executed, the element's #parents and #array_parents properties will have been set by the form API. For more documentation on #parents and #array_parents, see \Drupal\Core\Render\Element\FormElement.

Parameters

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

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form. Calling code should pass on a subform state created through \Drupal\Core\Form\SubformState::createForSubform().

Return value

array The form structure.

Overrides EmailWebformHandler::buildConfigurationForm

File

modules/webform_scheduled_email/src/Plugin/WebformHandler/ScheduleEmailWebformHandler.php, line 137

Class

ScheduleEmailWebformHandler
Schedules a webform submission's email.

Namespace

Drupal\webform_scheduled_email\Plugin\WebformHandler

Code

public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
  $webform = $this
    ->getWebform();

  // Get options, mail, and text elements as options (text/value).
  $date_element_options = [];
  $elements = $this->webform
    ->getElementsInitializedAndFlattened();
  foreach ($elements as $key => $element) {
    if (isset($element['#type']) && in_array($element['#type'], [
      'date',
      'datetime',
      'datelist',
    ])) {
      $title = isset($element['#title']) ? new FormattableMarkup('@title (@key)', [
        '@title' => $element['#title'],
        '@key' => $key,
      ]) : $key;
      $date_element_options["[webform_submission:values:{$key}:html_date]"] = $title;
    }
  }
  $form['scheduled'] = [
    '#type' => 'details',
    '#title' => $this
      ->t('Scheduled email'),
    '#open' => TRUE,
  ];

  // Display warning about submission log.
  if (!$webform
    ->hasSubmissionLog()) {
    $form['scheduled']['warning'] = [
      '#type' => 'webform_message',
      '#message_type' => 'error',
      '#message_message' => $this
        ->t('It is strongly recommended that <a href=":href">submission logging</a> is enable to track scheduled emails.', [
        ':href' => $webform
          ->toUrl('settings-submissions')
          ->toString(),
      ]),
      '#message_close' => TRUE,
      '#message_id' => 'webform_scheduled_email-' . $webform
        ->id(),
      '#message_storage' => WebformMessage::STORAGE_LOCAL,
    ];
  }

  // Send date/time.
  $send_options = [
    '[date:html_date]' => $this
      ->t('Current date'),
    WebformOtherBase::OTHER_OPTION => $this
      ->t('Custom @label…', [
      '@label' => $this->scheduledEmailManager
        ->getDateTypeLabel(),
    ]),
    (string) $this
      ->t('Webform') => [
      '[webform:open:html_date]' => $this
        ->t('Open date'),
      '[webform:close:html_date]' => $this
        ->t('Close date'),
    ],
    (string) $this
      ->t('Webform submission') => [
      '[webform_submission:created:html_date]' => $this
        ->t('Date created'),
      '[webform_submission:completed:html_date]' => $this
        ->t('Date completed'),
      '[webform_submission:changed:html_date]' => $this
        ->t('Date changed'),
    ],
  ];
  if ($date_element_options) {
    $send_options[(string) $this
      ->t('Element')] = $date_element_options;
  }
  $t_args = [
    '@format' => $this->scheduledEmailManager
      ->getDateFormatLabel(),
    '@type' => $this->scheduledEmailManager
      ->getDateTypeLabel(),
  ];
  $form['scheduled']['send'] = [
    '#type' => 'webform_select_other',
    '#title' => $this
      ->t('Send email on'),
    '#options' => $send_options,
    '#other__placeholder' => $this->scheduledEmailManager
      ->getDateFormatLabel(),
    '#other__description' => $this
      ->t('Enter a valid ISO @type (@format) or token which returns a valid ISO @type.', $t_args),
    '#default_value' => $this->configuration['send'],
  ];

  // Send days.
  $days_options = [];
  $days = [
    30,
    14,
    7,
    3,
    2,
    1,
  ];
  foreach ($days as $day) {
    $days_options["-{$day}"] = $this
      ->t('- @day days', [
      '@day' => $day,
    ]);
  }
  $days = array_reverse($days);
  foreach ($days as $day) {
    $days_options[$day] = $this
      ->t('+ @day days', [
      '@day' => $day,
    ]);
  }
  $form['scheduled']['days'] = [
    '#type' => 'webform_select_other',
    '#title' => $this
      ->t('Days'),
    '#title_display' => 'hidden',
    '#empty_option' => $this
      ->t('- None -'),
    '#options' => $days_options,
    '#default_value' => $this->configuration['days'],
    '#other__option_label' => $this
      ->t('Custom number of days…'),
    '#other__type' => 'number',
    '#other__field_suffix' => $this
      ->t('days'),
    '#other__placeholder' => $this
      ->t('Enter +/- days'),
  ];

  // Ignore past.
  $form['scheduled']['ignore_past'] = [
    '#type' => 'checkbox',
    '#title' => $this
      ->t('Do not schedule email if the action should be triggered in the past'),
    '#description' => $this
      ->t('You can use this setting to prevent an action to be scheduled if it should have been triggered in the past.'),
    '#default_value' => $this->configuration['ignore_past'],
    '#return_value' => TRUE,
  ];

  // Unschedule.
  $form['scheduled']['unschedule'] = [
    '#type' => 'checkbox',
    '#title' => $this
      ->t('Unschedule email when draft or submission is saved'),
    '#description' => $this
      ->t('You can use this setting to unschedule a draft reminder, when submission has been completed.'),
    '#default_value' => $this->configuration['unschedule'],
    '#return_value' => TRUE,
  ];

  // Queue all submissions.
  if ($webform
    ->hasSubmissions()) {
    $form['scheduled']['queue'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Schedule emails for all existing submissions'),
      '#description' => $this
        ->t('Check schedule emails after submissions have been processed.'),
      '#return_value' => TRUE,
      // Must specify #parents because 'queue' is not a configuration setting.
      // @see \Drupal\webform_scheduled_email\Plugin\WebformHandler\ScheduleEmailWebformHandler::defaultConfiguration
      // @see \Drupal\webform\Plugin\WebformHandlerBase::setSettingsParentsRecursively
      '#parents' => [
        'settings',
        'queue',
      ],
    ];
    $form['scheduled']['queue_message'] = [
      '#type' => 'webform_message',
      '#message_message' => $this
        ->t('Please note all submissions will be rescheduled, including ones that have already received an email from this handler and submissions whose send date is in the past.'),
      '#message_type' => 'warning',
      '#states' => [
        'visible' => [
          ':input[name="settings[queue]"]' => [
            'checked' => TRUE,
          ],
        ],
      ],
    ];
  }

  // Notes.
  $form['scheduled']['notes'] = [
    '#type' => 'details',
    '#title' => $this
      ->t('Please note'),
  ];
  $form['scheduled']['notes']['message'] = [
    '#theme' => 'item_list',
    '#items' => [
      $this
        ->t("Only one email can be scheduled per handler and submission."),
      $this
        ->t('Email will be rescheduled when a draft or submission is updated.'),
      $this
        ->t("Multiple handlers can be used to schedule multiple emails."),
      $this
        ->t('Deleting this handler will unschedule all scheduled emails.'),
      [
        '#markup' => $this
          ->t('Scheduled emails are automatically sent starting at midnight using <a href=":href">cron</a>, which is executed at predefined interval.', [
          ':href' => 'https://www.drupal.org/docs/7/setting-up-cron/overview',
        ]),
      ],
    ],
  ];
  $form['scheduled']['token_tree_link'] = $this
    ->buildTokenTreeElement();
  $form = parent::buildConfigurationForm($form, $form_state);

  // Change 'Send email' to 'Scheduled email'.
  $form['settings']['states']['#title'] = $this
    ->t('Schedule email');

  // Development.
  $form['development']['test_send'] = [
    '#type' => 'checkbox',
    '#title' => $this
      ->t('Immediately send email when testing a webform'),
    '#return_value' => TRUE,
    '#default_value' => $this->configuration['test_send'],
  ];
  return $this
    ->setSettingsParents($form);
}