You are here

abstract class WebformVariantFormBase in Webform 8.5

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

Provides a base webform for webform variants.

Hierarchy

Expanded class hierarchy of WebformVariantFormBase

File

src/Form/WebformVariantFormBase.php, line 19

Namespace

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

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

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

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

  /**
   * The webform variant.
   *
   * @var \Drupal\webform\Plugin\WebformVariantInterface
   */
  protected $webformVariant;

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

  /**
   * Constructs a WebformVariantFormBase.
   *
   * @param \Drupal\webform\WebformTokenManagerInterface $token_manager
   *   The webform token manager.
   */
  public function __construct(WebformTokenManagerInterface $token_manager) {
    $this->tokenManager = $token_manager;
  }

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

  /**
   * 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_variant
   *   The webform variant ID.
   *
   * @return array
   *   The form structure.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
   *   Throws not found exception if the number of variant instances for this
   *   webform exceeds the variant's cardinality.
   */
  public function buildForm(array $form, FormStateInterface $form_state, WebformInterface $webform = NULL, $webform_variant = NULL) {
    $this->webform = $webform;
    try {
      $this->webformVariant = $this
        ->prepareWebformVariant($webform_variant);
    } catch (PluginNotFoundException $e) {
      throw new NotFoundHttpException("Invalid variant id: '{$webform_variant}'.");
    }

    // Add meta data to webform variant form.
    // This information makes it a little easier to alter a variant's form.
    $form['#webform_id'] = $this->webform
      ->id();
    $form['#webform_variant_id'] = $this->webformVariant
      ->getVariantId();
    $form['#webform_variant_plugin_id'] = $this->webformVariant
      ->getPluginId();
    $request = $this
      ->getRequest();
    $form['description'] = [
      '#type' => 'container',
      'text' => [
        '#markup' => $this->webformVariant
          ->description(),
        '#prefix' => '<p>',
        '#suffix' => '</p>',
      ],
      '#weight' => -20,
    ];
    $form['id'] = [
      '#type' => 'value',
      '#value' => $this->webformVariant
        ->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->webformVariant
        ->getLabel(),
      '#required' => TRUE,
      '#attributes' => [
        'autofocus' => 'autofocus',
      ],
    ];
    $t_args = [
      '@requirements' => $this
        ->t('letters, numbers, underscores, and dashes'),
    ];
    $form['general']['variant_id'] = [
      '#type' => 'machine_name',
      '#maxlength' => static::MACHINE_NAME_MAXLENGHTH,
      '#description' => $this
        ->t('A unique name for this variant instance. Can only contain @requirements.', $t_args),
      '#default_value' => $this->webformVariant
        ->getVariantId(),
      '#required' => TRUE,
      '#disabled' => $this->webformVariant
        ->getVariantId() ? TRUE : FALSE,
      '#machine_name' => [
        'source' => [
          'general',
          'label',
        ],
        'exists' => [
          $this,
          'exists',
        ],
        'replace_pattern' => $this->webformVariant
          ->getMachineNameReplacePattern(),
        'replace' => $this->webformVariant
          ->getMachineNameReplace(),
        'error' => $this
          ->t('The element key name must contain only @requirements.', $t_args),
      ],
    ];

    // Only show variants select menu when there is more than
    // one variant available.
    $variant_options = $this
      ->getVariantElementsAsOptions();
    if (count($variant_options) === 1) {
      $form['general']['element_key'] = [
        '#type' => 'value',
        '#value' => key($variant_options),
      ];
      $form['general']['element_key_item'] = [
        '#title' => $this
          ->t('Element'),
        '#type' => 'item',
        '#markup' => reset($variant_options),
        '#access' => TRUE,
      ];
    }
    else {
      $form['general']['element_key'] = [
        '#type' => 'select',
        '#title' => $this
          ->t('Element'),
        '#options' => $variant_options,
        '#default_value' => $this->webformVariant
          ->getElementKey(),
        '#required' => TRUE,
      ];
    }
    $form['general']['notes'] = [
      '#type' => 'textarea',
      '#title' => $this
        ->t('Administrative notes'),
      '#description' => $this
        ->t("Entered text will be displayed on the variants administrative page."),
      '#rows' => 2,
      '#default_value' => $this->webformVariant
        ->getNotes(),
    ];
    $form['advanced'] = [
      '#type' => 'fieldset',
      '#title' => $this
        ->t('Advanced settings'),
      '#weight' => -10,
    ];
    $form['advanced']['status'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Enable the %name variant', [
        '%name' => $this->webformVariant
          ->label(),
      ]),
      '#return_value' => TRUE,
      '#default_value' => $this->webformVariant
        ->isEnabled(),
      // Disable broken plugins.
      '#disabled' => $this->webformVariant
        ->getPluginId() === 'broken',
    ];
    $form['#parents'] = [];
    $form['settings'] = [
      '#tree' => TRUE,
      '#parents' => [
        'settings',
      ],
    ];
    $subform_state = SubformState::createForSubform($form['settings'], $form, $form_state);
    $form['settings'] = $this->webformVariant
      ->buildConfigurationForm($form['settings'], $subform_state);

    // Get $form['settings']['#attributes']['novalidate'] and apply it to the
    // $form.
    // This allows variants 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;

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

    // Build tabs.
    $tabs = [
      '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 variant 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->webformVariant
      ->validateConfigurationForm($form, $subform_state);

    // Process variant state webform errors.
    $this
      ->processVariantFormErrors($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 variant 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->webformVariant
      ->submitConfigurationForm($form, $subform_state);

    // Update the original webform values.
    $form_state
      ->setValue('settings', $subform_state
      ->getValues());
    $this->webformVariant
      ->setVariantId($form_state
      ->getValue('variant_id'));
    $this->webformVariant
      ->setLabel($form_state
      ->getValue('label'));
    $this->webformVariant
      ->setNotes($form_state
      ->getValue('notes'));
    $this->webformVariant
      ->setElementKey($form_state
      ->getValue('element_key'));
    $this->webformVariant
      ->setStatus($form_state
      ->getValue('status'));
    $this->webformVariant
      ->setWeight($form_state
      ->getValue('weight'));
    if ($this instanceof WebformVariantAddForm) {
      $this->webform
        ->addWebformVariant($this->webformVariant);
      $this
        ->messenger()
        ->addStatus($this
        ->t('The webform variant was successfully added.'));
    }
    else {
      $this->webform
        ->updateWebformVariant($this->webformVariant);
      $this
        ->messenger()
        ->addStatus($this
        ->t('The webform variant was successfully updated.'));
    }
    $form_state
      ->setRedirectUrl($this->webform
      ->toUrl('variants', [
      'query' => [
        'update' => $this->webformVariant
          ->getVariantId(),
      ],
    ]));
  }

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

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

  /**
   * Get the webform variant.
   *
   * @return \Drupal\webform\Plugin\WebformVariantInterface
   *   A webform variant.
   */
  public function getWebformVariant() {
    return $this->webformVariant;
  }

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

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

  // Variant methods.

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

  /**
   * Get key/value array of webform variant elements.
   *
   * @return array
   *   A key/value array of webform variant elements.
   */
  protected function getVariantElementsAsOptions() {
    $webform = $this
      ->getWebform();
    $variant_plugin_id = $this
      ->getWebformVariant()
      ->getPluginId();
    $elements = $this
      ->getWebform()
      ->getElementsVariant();
    $options = [];
    foreach ($elements as $element_key) {
      $element = $webform
        ->getElement($element_key);
      if ($element['#variant'] === $variant_plugin_id) {
        $options[$element_key] = WebformElementHelper::getAdminTitle($element);
      }
    }
    return $options;
  }

}

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.
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::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
WebformVariantFormBase::$tokenManager protected property The token manager.
WebformVariantFormBase::$webform protected property The webform.
WebformVariantFormBase::$webformVariant protected property The webform variant.
WebformVariantFormBase::buildForm public function Form constructor. Overrides FormInterface::buildForm 2
WebformVariantFormBase::create public static function Instantiates a new instance of this class. Overrides FormBase::create 1
WebformVariantFormBase::exists public function Determines if the webform variant ID already exists.
WebformVariantFormBase::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
WebformVariantFormBase::getVariantElementsAsOptions protected function Get key/value array of webform variant elements.
WebformVariantFormBase::getWebform public function Get the webform variant's webform.
WebformVariantFormBase::getWebformVariant public function Get the webform variant.
WebformVariantFormBase::MACHINE_NAME_MAXLENGHTH constant Machine name maxlength.
WebformVariantFormBase::processVariantFormErrors protected function Process variant webform errors in webform.
WebformVariantFormBase::submitForm public function Form submission handler. Overrides FormInterface::submitForm
WebformVariantFormBase::validateForm public function Form validation handler. Overrides FormBase::validateForm
WebformVariantFormBase::__construct public function Constructs a WebformVariantFormBase. 1