You are here

class WebformEntityHandlersForm in Webform 8.5

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

Provides a webform to manage submission handlers.

Hierarchy

Expanded class hierarchy of WebformEntityHandlersForm

File

src/WebformEntityHandlersForm.php, line 21

Namespace

Drupal\webform
View source
class WebformEntityHandlersForm extends EntityForm {
  use WebformEntityAjaxFormTrait;

  /**
   * The webform.
   *
   * @var \Drupal\webform\WebformInterface
   */
  protected $entity;

  /**
   * The webform handler manager.
   *
   * @var \Drupal\webform\Plugin\WebformHandlerManagerInterface
   */
  protected $handlerManager;

  /**
   * Constructs a WebformEntityHandlersForm.
   *
   * @param \Drupal\webform\Plugin\WebformHandlerManagerInterface $handler_manager
   *   The webform handler manager.
   */
  public function __construct(WebformHandlerManagerInterface $handler_manager) {
    $this->handlerManager = $handler_manager;
  }

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

  /**
   * {@inheritdoc}
   */
  public function form(array $form, FormStateInterface $form_state) {
    $user_input = $form_state
      ->getUserInput();

    // Hard code the form id.
    $form['#id'] = 'webform-handlers-form';

    // Build table header.
    $header = [
      [
        'data' => $this
          ->t('Title / Description'),
      ],
      [
        'data' => $this
          ->t('ID'),
        'class' => [
          RESPONSIVE_PRIORITY_LOW,
        ],
      ],
      [
        'data' => $this
          ->t('Summary'),
        'class' => [
          RESPONSIVE_PRIORITY_LOW,
        ],
      ],
      [
        'data' => $this
          ->t('Status'),
        'class' => [
          RESPONSIVE_PRIORITY_LOW,
        ],
      ],
      [
        'data' => $this
          ->t('Weight'),
        'class' => [
          'webform-tabledrag-hide',
        ],
      ],
      [
        'data' => $this
          ->t('Operations'),
      ],
    ];

    // Build table rows for handlers.
    $handlers = $this->entity
      ->getHandlers();
    $rows = [];
    foreach ($handlers as $handler_id => $handler) {
      $offcanvas_dialog_attributes = WebformDialogHelper::getOffCanvasDialogAttributes($handler
        ->getOffCanvasWidth());
      $row['#attributes']['class'][] = 'draggable';
      $row['#attributes']['data-webform-key'] = $handler_id;
      $row['#weight'] = isset($user_input['handlers']) && isset($user_input['handlers'][$handler_id]) ? $user_input['handlers'][$handler_id]['weight'] : NULL;
      $row['handler'] = [
        '#tree' => FALSE,
        'data' => [
          'label' => [
            '#type' => 'link',
            '#title' => $handler
              ->label(),
            '#url' => Url::fromRoute('entity.webform.handler.edit_form', [
              'webform' => $this->entity
                ->id(),
              'webform_handler' => $handler_id,
            ]),
            '#attributes' => $offcanvas_dialog_attributes,
          ],
          'description' => [
            '#prefix' => '<br/>',
            '#markup' => $handler
              ->getNotes() ?: $handler
              ->description(),
          ],
        ],
      ];
      $row['id'] = [
        'data' => [
          '#markup' => $handler
            ->getHandlerId(),
        ],
      ];
      $row['summary'] = $handler
        ->getSummary();
      if ($handler
        ->isDisabled()) {
        $status = $this
          ->t('Disabled');
      }
      else {
        $status = $handler
          ->supportsConditions() && $handler
          ->getConditions() ? $this
          ->t('Conditional') : $this
          ->t('Enabled');
      }
      $row['status'] = [
        'data' => [
          '#markup' => $status,
        ],
      ];
      $row['weight'] = [
        '#type' => 'weight',
        '#title' => $this
          ->t('Weight for @title', [
          '@title' => $handler
            ->label(),
        ]),
        '#title_display' => 'invisible',
        '#delta' => 50,
        '#default_value' => $handler
          ->getWeight(),
        '#attributes' => [
          'class' => [
            'webform-handler-order-weight',
          ],
        ],
        '#wrapper_attributes' => [
          'class' => [
            'webform-tabledrag-hide',
          ],
        ],
      ];
      $operations = [];

      // Edit.
      $operations['edit'] = [
        'title' => $this
          ->t('Edit'),
        'url' => Url::fromRoute('entity.webform.handler.edit_form', [
          'webform' => $this->entity
            ->id(),
          'webform_handler' => $handler_id,
        ]),
        'attributes' => $offcanvas_dialog_attributes,
      ];

      // Duplicate.
      if ($handler
        ->cardinality() === WebformHandlerInterface::CARDINALITY_UNLIMITED) {
        $operations['duplicate'] = [
          'title' => $this
            ->t('Duplicate'),
          'url' => Url::fromRoute('entity.webform.handler.duplicate_form', [
            'webform' => $this->entity
              ->id(),
            'webform_handler' => $handler_id,
          ]),
          'attributes' => $offcanvas_dialog_attributes,
        ];
      }

      // Test individual handler.
      if ($this->entity
        ->access('test')) {
        $operations['test'] = [
          'title' => $this
            ->t('Test'),
          'url' => Url::fromRoute('entity.webform.test_form', [
            'webform' => $this->entity
              ->id(),
          ], [
            'query' => [
              '_webform_handler' => $handler_id,
            ],
          ]),
        ];
      }

      // Add AJAX functionality to enable/disable operations.
      $operations['status'] = [
        'title' => $handler
          ->isEnabled() ? $this
          ->t('Disable') : $this
          ->t('Enable'),
        'url' => Url::fromRoute('entity.webform.handler.' . ($handler
          ->isEnabled() ? 'disable' : 'enable'), [
          'webform' => $this->entity
            ->id(),
          'webform_handler' => $handler_id,
        ]),
        'attributes' => WebformDialogHelper::getModalDialogAttributes(WebformDialogHelper::DIALOG_NARROW, [
          'use-ajax',
        ]),
      ];

      // Delete.
      $operations['delete'] = [
        'title' => $this
          ->t('Delete'),
        'url' => Url::fromRoute('entity.webform.handler.delete_form', [
          'webform' => $this->entity
            ->id(),
          'webform_handler' => $handler_id,
        ]),
        'attributes' => WebformDialogHelper::getModalDialogAttributes(WebformDialogHelper::DIALOG_NARROW),
      ];
      $row['operations'] = [
        '#type' => 'operations',
        '#links' => $operations,
        '#prefix' => '<div class="webform-dropbutton">',
        '#suffix' => '</div>',
      ];
      $rows[$handler_id] = $row;
    }

    // Build the list of existing webform handlers for this webform.
    $form['handlers'] = [
      '#type' => 'table',
      '#header' => $header,
      '#tabledrag' => [
        [
          'action' => 'order',
          'relationship' => 'sibling',
          'group' => 'webform-handler-order-weight',
        ],
      ],
      '#attributes' => [
        'id' => 'webform-handlers',
        'class' => [
          'webform-handlers-table',
        ],
      ],
      '#empty' => $this
        ->t('There are currently no handlers setup for this webform.'),
    ] + $rows;

    // Must preload libraries required by (modal) dialogs.
    WebformDialogHelper::attachLibraries($form);
    $form['#attached']['library'][] = 'webform/webform.admin.tabledrag';
    return parent::form($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  protected function actionsElement(array $form, FormStateInterface $form_state) {
    $form = parent::actionsElement($form, $form_state);
    $form['submit']['#value'] = $this
      ->t('Save handlers');
    unset($form['delete']);
    return $form;
  }

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

    // Update webform handler weights.
    if (!$form_state
      ->isValueEmpty('handlers')) {
      $this
        ->updateHandlerWeights($form_state
        ->getValue('handlers'));
    }
    parent::submitForm($form, $form_state);
  }

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

    /** @var \Drupal\webform\WebformInterface $webform */
    $webform = $this
      ->getEntity();
    $webform
      ->save();
    $context = [
      '@label' => $webform
        ->label(),
      'link' => $webform
        ->toLink($this
        ->t('Edit'), 'handlers')
        ->toString(),
    ];
    $this
      ->logger('webform')
      ->notice('Webform @label handler saved.', $context);
    $this
      ->messenger()
      ->addStatus($this
      ->t('Webform %label handler saved.', [
      '%label' => $webform
        ->label(),
    ]));
  }

  /**
   * Updates webform handler weights.
   *
   * @param array $handlers
   *   Associative array with handlers having handler ids as keys and array
   *   with handler data as values.
   */
  protected function updateHandlerWeights(array $handlers) {
    foreach ($handlers as $handler_id => $handler_data) {
      if ($this->entity
        ->getHandlers()
        ->has($handler_id)) {
        $this->entity
          ->getHandler($handler_id)
          ->setWeight($handler_data['weight']);
      }
    }
  }

  /**
   * Calls a method on a webform handler and reloads the webform handlers form.
   *
   * @param \Drupal\webform\WebformInterface $webform
   *   The webform being acted upon.
   * @param string $webform_handler
   *   THe webform handler id.
   * @param string $operation
   *   The operation to perform, e.g., 'enable' or 'disable'.
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The current request.
   *
   * @return \Drupal\Core\Ajax\AjaxResponse|\Symfony\Component\HttpFoundation\RedirectResponse
   *   Either returns an AJAX response that refreshes the webform's handlers
   *   page, or redirects back to the webform's handlers page.
   */
  public static function ajaxOperation(WebformInterface $webform, $webform_handler, $operation, Request $request) {

    // Perform the handler disable/enable operation.
    $handler = $webform
      ->getHandler($webform_handler);
    $handler
      ->{$operation}();

    // Save the webform.
    $webform
      ->save();

    // Display message.
    $t_args = [
      '@label' => $handler
        ->label(),
      '@op' => $operation === 'enable' ? t('enabled') : t('disabled'),
    ];
    \Drupal::messenger()
      ->addStatus(t('This @label handler was @op.', $t_args));

    // Get the webform's handlers form URL.
    $url = $webform
      ->toUrl('handlers', [
      'query' => [
        'update' => $webform_handler,
      ],
    ])
      ->toString();

    // If the request is via AJAX, return the webform handlers form.
    if ($request->request
      ->get('js')) {
      $response = new AjaxResponse();
      $response
        ->addCommand(new WebformRefreshCommand($url));
      return $response;
    }

    // Otherwise, redirect back to the webform handlers form.
    return new RedirectResponse($url);
  }

}

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
EntityForm::$entityTypeManager protected property The entity type manager. 3
EntityForm::$moduleHandler protected property The module handler service.
EntityForm::$operation protected property The name of the current operation.
EntityForm::$privateEntityManager private property The entity manager.
EntityForm::afterBuild public function Form element #after_build callback: Updates the entity with submitted data.
EntityForm::buildEntity public function Builds an updated entity object based upon the submitted form values. Overrides EntityFormInterface::buildEntity 2
EntityForm::copyFormValuesToEntity protected function Copies top-level form values to entity properties 7
EntityForm::getBaseFormId public function Returns a string identifying the base form. Overrides BaseFormIdInterface::getBaseFormId 5
EntityForm::getEntity public function Gets the form entity. Overrides EntityFormInterface::getEntity
EntityForm::getEntityFromRouteMatch public function Determines which entity will be used by this form from a RouteMatch object. Overrides EntityFormInterface::getEntityFromRouteMatch 1
EntityForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId 10
EntityForm::getOperation public function Gets the operation identifying the form. Overrides EntityFormInterface::getOperation
EntityForm::init protected function Initialize the form state and the entity before the first form build. 3
EntityForm::prepareEntity protected function Prepares the entity object before the form is built first. 3
EntityForm::prepareInvokeAll protected function Invokes the specified prepare hook variant.
EntityForm::processForm public function Process callback: assigns weights and hides extra fields.
EntityForm::setEntity public function Sets the form entity. Overrides EntityFormInterface::setEntity
EntityForm::setEntityManager public function Sets the entity manager for this form. Overrides EntityFormInterface::setEntityManager
EntityForm::setEntityTypeManager public function Sets the entity type manager for this form. Overrides EntityFormInterface::setEntityTypeManager
EntityForm::setModuleHandler public function Sets the module handler for this form. Overrides EntityFormInterface::setModuleHandler
EntityForm::setOperation public function Sets the operation for this form. Overrides EntityFormInterface::setOperation
EntityForm::__get public function
EntityForm::__set public function
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.
WebformAjaxFormTrait::announce protected function Queue announcement with Ajax response.
WebformAjaxFormTrait::buildAjaxForm protected function Add Ajax support to a form.
WebformAjaxFormTrait::createAjaxResponse protected function Create an AjaxResponse or WebformAjaxResponse object.
WebformAjaxFormTrait::getAnnouncements protected function Get announcements.
WebformAjaxFormTrait::getFormStateRedirectUrl protected function Get redirect URL from the form's state.
WebformAjaxFormTrait::getWrapperId protected function Get the form's Ajax wrapper id. 1
WebformAjaxFormTrait::isCallableAjaxCallback protected function Determine if Ajax callback is callable.
WebformAjaxFormTrait::isDialog protected function Is the current request for an Ajax modal/dialog.
WebformAjaxFormTrait::isOffCanvasDialog protected function Is the current request for an off canvas dialog.
WebformAjaxFormTrait::missingAjaxCallback protected function Handle missing Ajax callback.
WebformAjaxFormTrait::noSubmit public function Empty submit callback used to only have the submit button to use an #ajax submit callback. 1
WebformAjaxFormTrait::resetAnnouncements protected function Reset announcements.
WebformAjaxFormTrait::setAnnouncements protected function Set announcements.
WebformAjaxFormTrait::submitAjaxForm public function Submit form #ajax callback. 1
WebformAjaxFormTrait::validateAjaxForm public function Validate form #ajax callback. 1
WebformEntityAjaxFormTrait::actions protected function
WebformEntityAjaxFormTrait::buildForm public function 1
WebformEntityAjaxFormTrait::cancelAjaxForm public function Cancel form #ajax callback. Overrides WebformAjaxFormTrait::cancelAjaxForm
WebformEntityAjaxFormTrait::getDefaultAjaxSettings protected function Get default ajax callback settings. Overrides WebformAjaxFormTrait::getDefaultAjaxSettings
WebformEntityAjaxFormTrait::isAjax protected function Returns if webform is using Ajax. Overrides WebformAjaxFormTrait::isAjax
WebformEntityAjaxFormTrait::isDialogDisabled protected function Determine if dialogs are disabled.
WebformEntityAjaxFormTrait::replaceForm protected function Replace form via an Ajax response. Overrides WebformAjaxFormTrait::replaceForm
WebformEntityHandlersForm::$entity protected property The webform. Overrides EntityForm::$entity
WebformEntityHandlersForm::$handlerManager protected property The webform handler manager.
WebformEntityHandlersForm::actionsElement protected function Returns the action form element for the current entity form. Overrides EntityForm::actionsElement
WebformEntityHandlersForm::ajaxOperation public static function Calls a method on a webform handler and reloads the webform handlers form.
WebformEntityHandlersForm::create public static function Instantiates a new instance of this class. Overrides FormBase::create
WebformEntityHandlersForm::form public function Gets the actual form array to be built. Overrides EntityForm::form
WebformEntityHandlersForm::save public function Form submission handler for the 'save' action. Overrides EntityForm::save
WebformEntityHandlersForm::submitForm public function This is the default entity object builder function. It is called before any other submit handler to build the new entity object to be used by the following submit handlers. At this point of the form workflow the entity is validated and the form state… Overrides EntityForm::submitForm
WebformEntityHandlersForm::updateHandlerWeights protected function Updates webform handler weights.
WebformEntityHandlersForm::__construct public function Constructs a WebformEntityHandlersForm.