contacts_events-8.x-1.x-dev/src/Form/AdminPaymentEmailFormAlter.php
src/Form/AdminPaymentEmailFormAlter.php
<?php namespace Drupal\contacts_events\Form; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\StringTranslation\StringTranslationTrait; use Drupal\Core\StringTranslation\TranslatableMarkup; /** * Form alter handler to add email confirmation to admin payment forms. */ class AdminPaymentEmailFormAlter { use StringTranslationTrait; /** * Form alter for the commerce payment form. * * @param array $form * The form array. * @param \Drupal\Core\Form\FormStateInterface $form_state * The form state. */ public function alter(array &$form, FormStateInterface $form_state) : void { $state_storage = $form_state->getStorage(); if (isset($state_storage['step']) && $state_storage['step'] == 'payment') { /** @var \Drupal\commerce_payment\Entity\PaymentInterface $payment */ $payment = $form['payment']['#inline_form']->getEntity(); if (!isset($form['actions']['#weight'])) { $form['actions']['#weight'] = 10; } $form['send_confirmation'] = [ '#type' => 'fieldset', '#title' => $this->t('Confirmation'), '#weight' => $form['actions']['#weight'] - 1, 'send' => [ '#type' => 'checkbox', '#title' => $this->t('Send payment confirmation'), ], 'send_to' => [ '#type' => 'email', '#title' => $this->t('Send confirmation to'), '#default_value' => $payment->getOrder()->get('mail')->value, '#states' => [ 'visible' => [ ':input[name="send_confirmation[send]"]' => ['checked' => TRUE], ], ], ], ]; $form['#validate'][] = [self::class, 'validateForm']; $form['#submit'][] = [self::class, 'submitForm']; } } /** * Validation handler for admin payment email notification. * * @param array $form * The form being submitted. * @param \Drupal\Core\Form\FormStateInterface $form_state * The state of the form. */ public static function validateForm(array &$form, FormStateInterface $form_state) : void { // phpcs:ignore Drupal.Arrays.Array.LongLineDeclaration if ($form_state->getValue(['send_confirmation', 'send']) && empty($form_state->getValue(['send_confirmation', 'send_to']))) { $form_state->setError($form['send_confirmation']['send_to'], new TranslatableMarkup('Confirmation email address is required to send a confirmation email.')); } } /** * Submission handler for admin payment email notification. * * @param array $form * The form being submitted. * @param \Drupal\Core\Form\FormStateInterface $form_state * The state of the form. */ public static function submitForm(array &$form, FormStateInterface $form_state) : void { if ($form_state->getValue(['send_confirmation', 'send'])) { $send_to = $form_state->getValue(['send_confirmation', 'send_to']); $payment = $form['payment']['#inline_form']->getEntity(); \Drupal::service('contacts_events.admin_payment_email_service')->sendToPayer($payment, $send_to); } } }