You are here

class WebformSubmissionResendForm in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Form/WebformSubmissionResendForm.php \Drupal\webform\Form\WebformSubmissionResendForm

Defines a webform that resends webform submission.

Hierarchy

Expanded class hierarchy of WebformSubmissionResendForm

2 string references to 'WebformSubmissionResendForm'
webform.routing.yml in ./webform.routing.yml
webform.routing.yml
webform_node.routing.yml in modules/webform_node/webform_node.routing.yml
modules/webform_node/webform_node.routing.yml

File

src/Form/WebformSubmissionResendForm.php, line 17

Namespace

Drupal\webform\Form
View source
class WebformSubmissionResendForm extends FormBase {
  use WebformAjaxElementTrait;

  /**
   * A webform submission.
   *
   * @var \Drupal\webform\WebformSubmissionInterface
   */
  protected $webformSubmission;

  /**
   * The source entity.
   *
   * @var \Drupal\Core\Entity\EntityInterface
   */
  protected $entity;

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'webform_submission_resend';
  }

  /**
   * The webform request handler.
   *
   * @var \Drupal\webform\WebformRequestInterface
   */
  protected $requestHandler;

  /**
   * Constructs a WebformResultsResendForm object.
   *
   * @param \Drupal\webform\WebformRequestInterface $request_handler
   *   The webform request handler.
   */
  public function __construct(WebformRequestInterface $request_handler) {
    $this->requestHandler = $request_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('webform.request'));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission = NULL) {
    $this->webformSubmission = $webform_submission;

    // Apply variants to the webform.
    $webform = $webform_submission
      ->getWebform();
    $webform
      ->applyVariants($webform_submission);

    // Get header.
    $header = [];
    $header['title'] = [
      'data' => $this
        ->t('Title / Description'),
    ];
    $header['id'] = [
      'data' => $this
        ->t('ID'),
      'class' => [
        RESPONSIVE_PRIORITY_LOW,
      ],
    ];
    $header['summary'] = [
      'data' => $this
        ->t('summary'),
      'class' => [
        RESPONSIVE_PRIORITY_LOW,
      ],
    ];
    $header['status'] = [
      'data' => $this
        ->t('Status'),
      'class' => [
        RESPONSIVE_PRIORITY_LOW,
      ],
    ];

    // Get options.
    $options = $this
      ->getMessageHandlerOptions($webform_submission);

    // Get message handler id from form state or use the first message handler.
    if (!empty($form_state
      ->getValue('message_handler_id'))) {
      $message_handler_id = $form_state
        ->getValue('message_handler_id');
    }
    else {
      $message_handler_id = key($options);
    }

    // Display message handler with change message Ajax submit button.
    $form['message_handler'] = [];
    $form['message_handler']['message_handler_id'] = [
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $options,
      '#js_select' => TRUE,
      '#empty' => $this
        ->t('No messages are available.'),
      '#multiple' => FALSE,
      '#default_value' => $message_handler_id,
    ];

    // Message.
    $message_handler = $this->webformSubmission
      ->getWebform()
      ->getHandler($message_handler_id);
    $message = $message_handler
      ->getMessage($webform_submission);
    $resend_form = $message_handler
      ->resendMessageForm($message);
    $form['message'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Message'),
      '#open' => TRUE,
      '#tree' => TRUE,
    ] + $resend_form;

    // Add resend button.
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Resend message'),
    ];

    // Add submission navigation.
    $source_entity = $this->requestHandler
      ->getCurrentSourceEntity('webform_submission');
    $form['navigation'] = [
      '#type' => 'webform_submission_navigation',
      '#webform_submission' => $webform_submission,
      '#weight' => -20,
    ];
    $form['information'] = [
      '#type' => 'webform_submission_information',
      '#webform_submission' => $webform_submission,
      '#source_entity' => $source_entity,
      '#weight' => -19,
    ];
    $form['#attached']['library'][] = 'webform/webform.admin';
    $this
      ->buildAjaxElement('webform-message-handler', $form['message'], $form['message_handler']['message_handler_id'], $form['message_handler']);
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $params = $form_state
      ->getValue('message');

    // Add webform submission.
    $params['webform_submission'] = $this->webformSubmission;
    $message_handler_id = $form_state
      ->getValue('message_handler_id');
    $message_handler = $this->webformSubmission
      ->getWebform()
      ->getHandler($message_handler_id);
    $message_handler
      ->sendMessage($this->webformSubmission, $params);
    $t_args = [
      '%label' => $message_handler
        ->label(),
    ];
    $this
      ->messenger()
      ->addStatus($this
      ->t('Successfully re-sent %label.', $t_args));
  }

  /**
   * Get message handler from webform state.
   *
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   *
   * @return \Drupal\webform\Plugin\WebformHandlerMessageInterface
   *   The current message handler.
   */
  protected function getMessageHandler(FormStateInterface $form_state) {
    $message_handler_id = $form_state
      ->getValue('message_handler_id');
    return $this->webformSubmission
      ->getWebform()
      ->getHandler($message_handler_id);
  }

  /****************************************************************************/

  // Helper methods.

  /****************************************************************************/

  /**
   * Get a webform submission's message handlers as options.
   *
   * @param \Drupal\webform\WebformSubmissionInterface $webform_submission
   *   A webform submission.
   *
   * @return array
   *   An associative array containing a webform submission's message handlers
   *   as table select options.
   */
  protected function getMessageHandlerOptions(WebformSubmissionInterface $webform_submission) {
    $handlers = $webform_submission
      ->getWebform()
      ->getHandlers();

    // Get options.
    $options = [];
    foreach ($handlers as $handler_id => $message_handler) {
      if (!$message_handler instanceof WebformHandlerMessageInterface) {
        continue;
      }
      $message = $message_handler
        ->getMessage($webform_submission);
      $options[$handler_id]['title'] = [
        'data' => [
          'label' => [
            '#type' => 'label',
            '#title' => $message_handler
              ->label() . ': ' . $message_handler
              ->description(),
            '#title_display' => NULL,
            '#for' => 'edit-message-handler-id-' . str_replace('_', '-', $message_handler
              ->getHandlerId()),
          ],
        ],
      ];
      $options[$handler_id]['id'] = [
        'data' => $message_handler
          ->getHandlerId(),
      ];
      $options[$handler_id]['summary'] = [
        'data' => $message_handler
          ->getMessageSummary($message),
      ];
      $options[$handler_id]['status'] = $message_handler
        ->isEnabled() ? $this
        ->t('Enabled') : $this
        ->t('Disabled');
    }
    return $options;
  }

  /****************************************************************************/

  // Change message ajax callbacks.

  /****************************************************************************/

  /**
   * {@inheritdoc}
   */
  public static function submitAjaxElementCallback(array $form, FormStateInterface $form_state) {

    // Unset the message so that it can be completely rebuilt.
    NestedArray::unsetValue($form_state
      ->getUserInput(), [
      'message',
    ]);
    $form_state
      ->unsetValue('message');

    // Rebuild the form.
    $form_state
      ->setRebuild();
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.
WebformAjaxElementTrait::buildAjaxElement public function Build an Ajax element.
WebformAjaxElementTrait::buildAjaxElementTrigger public function Build an Ajax element's trigger.
WebformAjaxElementTrait::buildAjaxElementUpdate public function Build an Ajax element's update (submit) button.
WebformAjaxElementTrait::buildAjaxElementWrapper public function Build an Ajax element's wrapper.
WebformAjaxElementTrait::getAjaxElementUpdateClass public function Get Ajax element update class.
WebformAjaxElementTrait::getAjaxElementUpdateName public function Get Ajax element update name.
WebformAjaxElementTrait::getAjaxElementWrapperId public function Get Ajax element wrapper id.
WebformAjaxElementTrait::getAjaxElementWrapperRecursive protected static function Get ajax element wrapper.
WebformAjaxElementTrait::updateAjaxElementCallback public static function Ajax element update callback.
WebformAjaxElementTrait::validateAjaxElementCallback public static function Ajax element validate callback.
WebformSubmissionResendForm::$entity protected property The source entity.
WebformSubmissionResendForm::$requestHandler protected property The webform request handler.
WebformSubmissionResendForm::$webformSubmission protected property A webform submission.
WebformSubmissionResendForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
WebformSubmissionResendForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
WebformSubmissionResendForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
WebformSubmissionResendForm::getMessageHandler protected function Get message handler from webform state.
WebformSubmissionResendForm::getMessageHandlerOptions protected function Get a webform submission's message handlers as options.
WebformSubmissionResendForm::submitAjaxElementCallback public static function Ajax element submit callback. Overrides WebformAjaxElementTrait::submitAjaxElementCallback
WebformSubmissionResendForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
WebformSubmissionResendForm::__construct public function Constructs a WebformResultsResendForm object.