abstract class WebformVariantFormBase in Webform 8.5
Same name and namespace in other branches
- 6.x src/Form/WebformVariantFormBase.php \Drupal\webform\Form\WebformVariantFormBase
Provides a base webform for webform variants.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, LinkGeneratorTrait, RedirectDestinationTrait, UrlGeneratorTrait, StringTranslationTrait- class \Drupal\webform\Form\WebformVariantFormBase uses WebformDialogFormTrait
 
Expanded class hierarchy of WebformVariantFormBase
File
- src/Form/ WebformVariantFormBase.php, line 19 
Namespace
Drupal\webform\FormView 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
| Name   | Modifiers | Type | Description | Overrides | 
|---|---|---|---|---|
| DependencySerializationTrait:: | protected | property | An array of entity type IDs keyed by the property name of their storages. | |
| DependencySerializationTrait:: | protected | property | An array of service IDs keyed by property name used for serialization. | |
| DependencySerializationTrait:: | public | function | 1 | |
| DependencySerializationTrait:: | public | function | 2 | |
| FormBase:: | protected | property | The config factory. | 1 | 
| FormBase:: | protected | property | The request stack. | 1 | 
| FormBase:: | protected | property | The route match. | |
| FormBase:: | protected | function | Retrieves a configuration object. | |
| FormBase:: | protected | function | Gets the config factory for this form. | 1 | 
| FormBase:: | private | function | Returns the service container. | |
| FormBase:: | protected | function | Gets the current user. | |
| FormBase:: | protected | function | Gets the request object. | |
| FormBase:: | protected | function | Gets the route match. | |
| FormBase:: | protected | function | Gets the logger for a specific channel. | |
| FormBase:: | protected | function | Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait:: | |
| FormBase:: | public | function | Resets the configuration factory. | |
| FormBase:: | public | function | Sets the config factory for this form. | |
| FormBase:: | public | function | Sets the request stack object to use. | |
| LinkGeneratorTrait:: | protected | property | The link generator. | 1 | 
| LinkGeneratorTrait:: | protected | function | Returns the link generator. | |
| LinkGeneratorTrait:: | protected | function | Renders a link to a route given a route name and its parameters. | |
| LinkGeneratorTrait:: | public | function | Sets the link generator service. | |
| LoggerChannelTrait:: | protected | property | The logger channel factory service. | |
| LoggerChannelTrait:: | protected | function | Gets the logger for a specific channel. | |
| LoggerChannelTrait:: | public | function | Injects the logger channel factory. | |
| MessengerTrait:: | protected | property | The messenger. | 29 | 
| MessengerTrait:: | public | function | Gets the messenger. | 29 | 
| MessengerTrait:: | public | function | Sets the messenger. | |
| RedirectDestinationTrait:: | protected | property | The redirect destination service. | 1 | 
| RedirectDestinationTrait:: | protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
| RedirectDestinationTrait:: | protected | function | Returns the redirect destination service. | |
| RedirectDestinationTrait:: | public | function | Sets the redirect destination service. | |
| StringTranslationTrait:: | protected | property | The string translation service. | 1 | 
| StringTranslationTrait:: | protected | function | Formats a string containing a count of items. | |
| StringTranslationTrait:: | protected | function | Returns the number of plurals supported by a given language. | |
| StringTranslationTrait:: | protected | function | Gets the string translation service. | |
| StringTranslationTrait:: | public | function | Sets the string translation service to use. | 2 | 
| StringTranslationTrait:: | protected | function | Translates a string to the current language or to a given language. | |
| UrlGeneratorTrait:: | protected | property | The url generator. | |
| UrlGeneratorTrait:: | protected | function | Returns the URL generator service. | |
| UrlGeneratorTrait:: | public | function | Sets the URL generator service. | |
| UrlGeneratorTrait:: | protected | function | Generates a URL or path for a specific route based on the given parameters. | |
| WebformAjaxFormTrait:: | protected | function | Queue announcement with Ajax response. | |
| WebformAjaxFormTrait:: | protected | function | Add Ajax support to a form. | |
| WebformAjaxFormTrait:: | protected | function | Create an AjaxResponse or WebformAjaxResponse object. | |
| WebformAjaxFormTrait:: | protected | function | Get announcements. | |
| WebformAjaxFormTrait:: | protected | function | Get default ajax callback settings. | 1 | 
| WebformAjaxFormTrait:: | protected | function | Get redirect URL from the form's state. | |
| WebformAjaxFormTrait:: | protected | function | Get the form's Ajax wrapper id. | 1 | 
| WebformAjaxFormTrait:: | protected | function | Determine if Ajax callback is callable. | |
| WebformAjaxFormTrait:: | protected | function | Is the current request for an Ajax modal/dialog. | |
| WebformAjaxFormTrait:: | protected | function | Is the current request for an off canvas dialog. | |
| WebformAjaxFormTrait:: | protected | function | Handle missing Ajax callback. | |
| WebformAjaxFormTrait:: | protected | function | Replace form via an Ajax response. | 1 | 
| WebformAjaxFormTrait:: | protected | function | Reset announcements. | |
| WebformAjaxFormTrait:: | protected | function | Set announcements. | |
| WebformAjaxFormTrait:: | public | function | Submit form #ajax callback. | 1 | 
| WebformAjaxFormTrait:: | public | function | Validate form #ajax callback. | 1 | 
| WebformDialogFormTrait:: | protected | function | Add modal dialog support to a confirm form. | |
| WebformDialogFormTrait:: | protected | function | Build webform dialog delete link. | |
| WebformDialogFormTrait:: | protected | function | Add modal dialog support to a form. | |
| WebformDialogFormTrait:: | public | function | Cancel form #ajax callback. Overrides WebformAjaxFormTrait:: | 1 | 
| WebformDialogFormTrait:: | public | function | Close dialog. | |
| WebformDialogFormTrait:: | protected | function | Returns if webform is using Ajax. Overrides WebformAjaxFormTrait:: | 1 | 
| WebformDialogFormTrait:: | public | function | Empty submit callback used to only have the submit button to use an #ajax submit callback. Overrides WebformAjaxFormTrait:: | |
| WebformDialogFormTrait:: | public | function | Validate callback to clear validation errors. | 2 | 
| WebformVariantFormBase:: | protected | property | The token manager. | |
| WebformVariantFormBase:: | protected | property | The webform. | |
| WebformVariantFormBase:: | protected | property | The webform variant. | |
| WebformVariantFormBase:: | public | function | Form constructor. Overrides FormInterface:: | 2 | 
| WebformVariantFormBase:: | public static | function | Instantiates a new instance of this class. Overrides FormBase:: | 1 | 
| WebformVariantFormBase:: | public | function | Determines if the webform variant ID already exists. | |
| WebformVariantFormBase:: | public | function | Returns a unique string identifying the form. Overrides FormInterface:: | |
| WebformVariantFormBase:: | protected | function | Get key/value array of webform variant elements. | |
| WebformVariantFormBase:: | public | function | Get the webform variant's webform. | |
| WebformVariantFormBase:: | public | function | Get the webform variant. | |
| WebformVariantFormBase:: | constant | Machine name maxlength. | ||
| WebformVariantFormBase:: | protected | function | Process variant webform errors in webform. | |
| WebformVariantFormBase:: | public | function | Form submission handler. Overrides FormInterface:: | |
| WebformVariantFormBase:: | public | function | Form validation handler. Overrides FormBase:: | |
| WebformVariantFormBase:: | public | function | Constructs a WebformVariantFormBase. | 1 | 
