You are here

abstract class WebformHandlerFormBase in Webform 6.x

Same name and namespace in other branches
  1. 8.5 src/Form/WebformHandlerFormBase.php \Drupal\webform\Form\WebformHandlerFormBase

Provides a base webform for webform handlers.

Hierarchy

Expanded class hierarchy of WebformHandlerFormBase

File

src/Form/WebformHandlerFormBase.php, line 19

Namespace

Drupal\webform\Form
View source
abstract class WebformHandlerFormBase extends FormBase {
  use WebformDialogFormTrait;

  /**
   * Machine name maxlength.
   */
  const MACHINE_NAME_MAXLENGTH = 64;

  /**
   * The language manager.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * The transliteration helper.
   *
   * @var \Drupal\Component\Transliteration\TransliterationInterface
   */
  protected $transliteration;

  /**
   * The token manager.
   *
   * @var \Drupal\webform\WebformTokenManagerInterface
   */
  protected $tokenManager;

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

  /**
   * The webform handler.
   *
   * @var \Drupal\webform\Plugin\WebformHandlerInterface
   */
  protected $webformHandler;

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

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->languageManager = $container
      ->get('language_manager');
    $instance->transliteration = $container
      ->get('transliteration');
    $instance->tokenManager = $container
      ->get('webform.token_manager');
    return $instance;
  }

  /**
   * Form constructor.
   *
   * @param array $form
   *   An associative array containing the structure of the form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The current state of the form.
   * @param \Drupal\webform\WebformInterface $webform
   *   The webform.
   * @param string $webform_handler
   *   The webform handler ID.
   *
   * @return array
   *   The form structure.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   Throws not found exception if the number of handler instances for this
   *   webform exceeds the handler's cardinality.
   */
  public function buildForm(array $form, FormStateInterface $form_state, WebformInterface $webform = NULL, $webform_handler = NULL) {
    $this->webform = $webform;
    try {
      $this->webformHandler = $this
        ->prepareWebformHandler($webform_handler);
    } catch (PluginNotFoundException $e) {
      throw new NotFoundHttpException("Invalid handler id: '{$webform_handler}'.");
    }

    // Limit the number of plugin instanced allowed.
    if (!$this->webformHandler
      ->getHandlerId()) {
      $plugin_id = $this->webformHandler
        ->getPluginId();
      $cardinality = $this->webformHandler
        ->cardinality();
      $number_of_instances = $webform
        ->getHandlers($plugin_id)
        ->count();
      if ($cardinality !== WebformHandlerInterface::CARDINALITY_UNLIMITED && $cardinality <= $number_of_instances) {
        throw new NotFoundHttpException($this
          ->formatPlural($cardinality, 'Only @count instance is permitted', 'Only @count instances are permitted'));
      }
    }

    // Add meta data to webform handler form.
    // This information makes it a little easier to alter a handler's form.
    $form['#webform_id'] = $this->webform
      ->id();
    $form['#webform_handler_id'] = $this->webformHandler
      ->getHandlerId();
    $form['#webform_handler_plugin_id'] = $this->webformHandler
      ->getPluginId();
    $request = $this
      ->getRequest();
    $form['description'] = [
      '#type' => 'container',
      'text' => [
        '#markup' => $this->webformHandler
          ->description(),
        '#prefix' => '<p>',
        '#suffix' => '</p>',
      ],
      '#weight' => -20,
    ];
    $form['id'] = [
      '#type' => 'value',
      '#value' => $this->webformHandler
        ->getPluginId(),
    ];
    $form['general'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('General settings'),
      '#weight' => -10,
    ];
    $form['general']['label'] = [
      '#type' => 'textfield',
      '#title' => $this
        ->t('Title'),
      '#maxlength' => 255,
      '#default_value' => $this->webformHandler
        ->label(),
      '#required' => TRUE,
      '#attributes' => [
        'autofocus' => 'autofocus',
      ],
    ];
    $form['general']['handler_id'] = [
      '#type' => 'machine_name',
      '#maxlength' => static::MACHINE_NAME_MAXLENGTH,
      '#description' => $this
        ->t('A unique name for this handler instance. Must be alpha-numeric and underscore separated.'),
      '#default_value' => $this->webformHandler
        ->getHandlerId() ?: NULL,
      '#required' => TRUE,
      '#disabled' => $this->webformHandler
        ->getHandlerId() ? TRUE : FALSE,
      '#machine_name' => [
        'source' => [
          'general',
          'label',
        ],
        'exists' => [
          $this,
          'exists',
        ],
      ],
      '#element_validate' => [
        [
          $this,
          'validateMachineName',
        ],
        [
          MachineName::class,
          'validateMachineName',
        ],
      ],
    ];
    $form['general']['notes'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Administrative notes'),
      '#description' => $this
        ->t("Entered text will be displayed on the handlers administrative page and replace this handler's default description."),
      '#rows' => 2,
      '#default_value' => $this->webformHandler
        ->getNotes(),
    ];
    $form['advanced'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Advanced settings'),
      '#weight' => -10,
    ];
    $form['advanced']['status'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable the %name handler.', [
        '%name' => $this->webformHandler
          ->label(),
      ]),
      '#return_value' => TRUE,
      '#default_value' => $this->webformHandler
        ->isEnabled(),
      // Disable broken plugins.
      '#disabled' => $this->webformHandler
        ->getPluginId() === 'broken',
    ];
    $form['#parents'] = [];
    $form['settings'] = [
      '#tree' => TRUE,
      '#parents' => [
        'settings',
      ],
    ];
    $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
    $form['settings'] = $this->webformHandler
      ->buildConfigurationForm($form['settings'], $subform_state);

    // Get $form['settings']['#attributes']['novalidate'] and apply it to the
    // $form.
    // This allows handlers with hide/show logic to skip HTML5 validation.
    // @see http://stackoverflow.com/questions/22148080/an-invalid-form-control-with-name-is-not-focusable
    if (isset($form['settings']['#attributes']['novalidate'])) {
      $form['#attributes']['novalidate'] = 'novalidate';
    }
    $form['settings']['#tree'] = TRUE;

    // Conditional logic.
    if ($this->webformHandler
      ->supportsConditions()) {
      $form['conditional_logic'] = [
        '#type' => 'fieldset',
        '#title' => $this
          ->t('Conditional logic'),
      ];
      $form['conditional_logic']['conditions'] = [
        '#type' => 'webform_element_states',
        '#state_options' => [
          'enabled' => $this
            ->t('Enabled'),
          'disabled' => $this
            ->t('Disabled'),
        ],
        '#selector_options' => $webform
          ->getElementsSelectorOptions([
          'excluded_elements' => [],
        ]),
        '#selector_sources' => $webform
          ->getElementsSelectorSourceValues(),
        '#multiple' => FALSE,
        '#default_value' => $this->webformHandler
          ->getConditions(),
      ];
    }

    // Check the URL for a weight, then the webform handler,
    // otherwise use default.
    $form['weight'] = [
      '#type' => 'hidden',
      '#value' => $request->query
        ->has('weight') ? (int) $request->query
        ->get('weight') : $this->webformHandler
        ->getWeight(),
    ];

    // Build tabs.
    $tabs = [
      'conditions' => [
        'title' => $this
          ->t('Conditions'),
        'elements' => [
          'conditional_logic',
        ],
        'weight' => 10,
      ],
      'advanced' => [
        'title' => $this
          ->t('Advanced'),
        'elements' => [
          'advanced',
          'additional',
          'development',
        ],
        'weight' => 20,
      ],
    ];
    $form = WebformFormHelper::buildTabs($form, $tabs);
    $form['actions'] = [
      '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Save'),
      '#button_type' => 'primary',
    ];

    // Add token links below the form and on every tab.
    $form['token_tree_link'] = $this->tokenManager
      ->buildTreeElement();
    if ($form['token_tree_link']) {
      $form['token_tree_link'] += [
        '#weight' => 101,
      ];
    }
    return $this
      ->buildDialogForm($form, $form_state);
  }

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

    // The webform handler configuration is stored in the 'settings' key in
    // the webform, pass that through for validation.
    $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
    $this->webformHandler
      ->validateConfigurationForm($form, $subform_state);

    // Process handler state webform errors.
    $this
      ->processHandlerFormErrors($subform_state, $form_state);

    // Update the original webform values.
    $form_state
      ->setValue('settings', $subform_state
      ->getValues());
  }

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

    // The webform handler configuration is stored in the 'settings' key in
    // the webform, pass that through for submission.
    $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
    $this->webformHandler
      ->submitConfigurationForm($form, $subform_state);

    // Update the original webform values.
    $form_state
      ->setValue('settings', $subform_state
      ->getValues());
    $this->webformHandler
      ->setHandlerId($form_state
      ->getValue('handler_id'));
    $this->webformHandler
      ->setLabel($form_state
      ->getValue('label'));
    $this->webformHandler
      ->setNotes($form_state
      ->getValue('notes'));
    $this->webformHandler
      ->setStatus($form_state
      ->getValue('status'));
    $this->webformHandler
      ->setWeight($form_state
      ->getValue('weight'));

    // Clear conditions if conditions or handler is disabled.
    if (!$this->webformHandler
      ->supportsConditions() || $this->webformHandler
      ->isDisabled()) {
      $this->webformHandler
        ->setConditions([]);
    }
    else {
      $this->webformHandler
        ->setConditions($form_state
        ->getValue('conditions'));
    }
    if ($this instanceof WebformHandlerAddForm) {
      $this->webform
        ->addWebformHandler($this->webformHandler);
      $this
        ->messenger()
        ->addStatus($this
        ->t('The webform handler was successfully added.'));
    }
    else {
      $this->webform
        ->updateWebformHandler($this->webformHandler);
      $this
        ->messenger()
        ->addStatus($this
        ->t('The webform handler was successfully updated.'));
    }
    $form_state
      ->setRedirectUrl($this->webform
      ->toUrl('handlers', [
      'query' => [
        'update' => $this->webformHandler
          ->getHandlerId(),
      ],
    ]));
  }

  /**
   * Validates the machine name for a webform handler instance.
   *
   * This method verifies the uniqueness of the machine name and updates the
   * machine name with a count suffix if another handler with the same machine
   * name already exists.
   *
   * @see \Drupal\Core\Render\Element\MachineName::validateMachineName()
   */
  public function validateMachineName(&$element, FormStateInterface $form_state, &$complete_form) {

    // If the machine name matches the default machine name, it does not need to
    // be validated (i.e. during handler edit form save).
    if (isset($element['#default_value']) && $element['#default_value'] === $element['#value']) {
      return;
    }
    $count = 1;
    $machine_name = $element['#value'];
    $instance_ids = $this->webform
      ->getHandlers()
      ->getInstanceIds();
    while (isset($instance_ids[$machine_name])) {
      $machine_name = $element['#value'] . '_' . $count++;
    }
    $element['#value'] = $machine_name;
    $form_state
      ->setValueForElement($element, $machine_name);
  }

  /**
   * Determines if the webform handler ID already exists.
   *
   * @param string $handler_id
   *   The webform handler ID.
   *
   * @return bool
   *   TRUE if the webform handler ID exists, FALSE otherwise.
   */
  public function exists($handler_id) {
    $instance_ids = $this->webform
      ->getHandlers()
      ->getInstanceIds();
    return isset($instance_ids[$handler_id]) ? TRUE : FALSE;
  }

  /**
   * Get the webform handler's webform.
   *
   * @return \Drupal\webform\WebformInterface
   *   A webform.
   */
  public function getWebform() {
    return $this->webform;
  }

  /**
   * Get the webform handler.
   *
   * @return \Drupal\webform\Plugin\WebformHandlerInterface
   *   A webform handler.
   */
  public function getWebformHandler() {
    return $this->webformHandler;
  }

  /**
   * Process handler webform errors in webform.
   *
   * @param \Drupal\Core\Form\FormStateInterface $handler_state
   *   The webform handler webform state.
   * @param \Drupal\Core\Form\FormStateInterface &$form_state
   *   The webform state.
   */
  protected function processHandlerFormErrors(FormStateInterface $handler_state, FormStateInterface &$form_state) {
    foreach ($handler_state
      ->getErrors() as $name => $message) {
      $form_state
        ->setErrorByName($name, $message);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
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. 3
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.
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.
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. 27
MessengerTrait::messenger public function Gets the messenger. 27
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. 4
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.
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::getDefaultAjaxSettings protected function Get default ajax callback settings. 1
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::replaceForm protected function Replace form via an Ajax response. 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
WebformDialogFormTrait::buildDialogConfirmForm protected function Add modal dialog support to a confirm form.
WebformDialogFormTrait::buildDialogDeleteAction protected function Build webform dialog delete link.
WebformDialogFormTrait::buildDialogForm protected function Add modal dialog support to a form.
WebformDialogFormTrait::cancelAjaxForm public function Cancel form #ajax callback. Overrides WebformAjaxFormTrait::cancelAjaxForm 1
WebformDialogFormTrait::closeDialog public function Close dialog.
WebformDialogFormTrait::isAjax protected function Returns if webform is using Ajax. Overrides WebformAjaxFormTrait::isAjax 1
WebformDialogFormTrait::noSubmit public function Empty submit callback used to only have the submit button to use an #ajax submit callback. Overrides WebformAjaxFormTrait::noSubmit
WebformDialogFormTrait::noValidate public function Validate callback to clear validation errors. 2
WebformHandlerFormBase::$languageManager protected property The language manager.
WebformHandlerFormBase::$tokenManager protected property The token manager.
WebformHandlerFormBase::$transliteration protected property The transliteration helper.
WebformHandlerFormBase::$webform protected property The webform.
WebformHandlerFormBase::$webformHandler protected property The webform handler.
WebformHandlerFormBase::buildForm public function Form constructor. Overrides FormInterface::buildForm 2
WebformHandlerFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 1
WebformHandlerFormBase::exists public function Determines if the webform handler ID already exists.
WebformHandlerFormBase::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
WebformHandlerFormBase::getWebform public function Get the webform handler's webform.
WebformHandlerFormBase::getWebformHandler public function Get the webform handler.
WebformHandlerFormBase::MACHINE_NAME_MAXLENGTH constant Machine name maxlength.
WebformHandlerFormBase::processHandlerFormErrors protected function Process handler webform errors in webform.
WebformHandlerFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm
WebformHandlerFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
WebformHandlerFormBase::validateMachineName public function Validates the machine name for a webform handler instance.