You are here

class FormBuilder in Secure Pages 8

FormBuilder decorator for the core formbuilder.

Hierarchy

Expanded class hierarchy of FormBuilder

1 string reference to 'FormBuilder'
securepages.services.yml in ./securepages.services.yml
securepages.services.yml
1 service uses FormBuilder
securepages.form_builder in ./securepages.services.yml
Drupal\securepages\FormBuilder

File

src/FormBuilder.php, line 17
Contains \Drupal\securepages\FormBuilder.

Namespace

Drupal\securepages
View source
class FormBuilder extends CoreFormBuilder {

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

    // Override \Drupal\Core\Form\FormBuilder::renderPlaceholderFormAction(),
    // the default form action lazy builder, with Secure Pages' variant. Since
    // Secure Pages allows specific forms to opt in, we need to not only
    // override the #lazy_builder callback but also the arguments: the form ID
    // also needs to be known.
    // Only update the action if it is not already set.
    $config = \Drupal::config('securepages.settings');
    if ($config
      ->get('enabled') && !isset($form['#action'])) {

      // Instead of setting an actual action URL, we set the placeholder, which
      // will be replaced at the very last moment. This ensures forms with
      // dynamically generated action URLs don't have poor cacheability.
      // Use the proper API to generate the placeholder, when we have one. See
      // https://www.drupal.org/node/2562341.
      $placeholder = 'form_action_' . hash('crc32b', __METHOD__);

      //      $form['#attached']['placeholders'][$placeholder] = [
      //        '#lazy_builder' => ['securepages.form_builder:renderPlaceholderFormAction', [$form_id]],
      //      ];
      $form['#action'] = $placeholder;
    }
    return parent::prepareForm($form_id, $form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function renderPlaceholderFormAction($form_id = '') {

    // This duplicates the logic of the parent method. We need to duplicate it
    // because we need to pass an additional argument to ::buildFormAction().
    $form_action = [
      '#type' => 'markup',
      '#markup' => $this
        ->buildFormAction($form_id),
      '#cache' => [
        'contexts' => [
          'url.path',
          'url.query_args',
        ],
      ],
    ];

    // Due to dependency on Request::isSecure().
    $form_action['#cache']['contexts'][] = 'url.site';

    // Due to dependency on \Drupal\securepages\Securepages::matchCurrentUser().
    $form_action['#cache']['contexts'][] = 'user.roles';

    // The generated form action depends on the Secure Pages configuration.
    $cacheability = new CacheableMetadata();
    $cacheability
      ->addCacheableDependency(\Drupal::config('securepages.settings'));
    $cacheability
      ->applyTo($form_action);
    return $form_action;
  }

  /**
   * {@inheritdoc}
   */
  protected function buildFormAction($form_id = '') {
    $url = parent::buildFormAction();
    $request = $this->requestStack
      ->getCurrentRequest();
    $config = \Drupal::config('securepages.settings');
    $is_https = $request
      ->isSecure();
    $path = \Drupal::service('path.current')
      ->getPath($request);
    $path_match = Securepages::matchPath($path);
    $role_match = Securepages::matchCurrentUser();
    $form_match = Securepages::matchFormId($form_id);
    if ($role_match || $path_match && !$is_https || !(!$path_match && $is_https && $config
      ->get('switch')) || $form_match) {
      $url = rtrim(Securepages::getUrl('<front>')
        ->toString(), '/') . $url;
    }
    return $url;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
FormBuilder::$classResolver protected property The class resolver.
FormBuilder::$csrfToken protected property The CSRF token generator to validate the form token.
FormBuilder::$currentUser protected property The current user.
FormBuilder::$elementInfo protected property The element info manager.
FormBuilder::$eventDispatcher protected property The event dispatcher.
FormBuilder::$formCache protected property The form cache.
FormBuilder::$formSubmitter protected property The form submitter.
FormBuilder::$formValidator protected property The form validator.
FormBuilder::$moduleHandler protected property The module handler.
FormBuilder::$requestStack protected property The request stack.
FormBuilder::$safeCoreValueCallables protected property Defines element value callables which are safe to run even when the form state has an invalid CSRF token.
FormBuilder::$themeManager protected property The theme manager.
FormBuilder::buildForm public function Builds and processes a form for a given form ID. Overrides FormBuilderInterface::buildForm
FormBuilder::buildFormAction protected function Builds the $form['#action']. Overrides FormBuilder::buildFormAction
FormBuilder::buttonWasClicked protected function Determines if a given button triggered the form submission.
FormBuilder::currentUser protected function Gets the current active user.
FormBuilder::deleteCache public function Deletes a form in the cache. Overrides FormCacheInterface::deleteCache
FormBuilder::doBuildForm public function Builds and processes all elements in the structured form array. Overrides FormBuilderInterface::doBuildForm
FormBuilder::doSubmitForm public function Handles the submitted form, executing callbacks and processing responses. Overrides FormSubmitterInterface::doSubmitForm
FormBuilder::elementTriggeredScriptedSubmission protected function Detects if an element triggered the form submission via Ajax.
FormBuilder::executeSubmitHandlers public function Executes custom submission handlers for a given form. Overrides FormSubmitterInterface::executeSubmitHandlers
FormBuilder::executeValidateHandlers public function Executes custom validation handlers for a given form. Overrides FormValidatorInterface::executeValidateHandlers
FormBuilder::getCache public function Fetches a form from the cache. Overrides FormCacheInterface::getCache
FormBuilder::getFileUploadMaxSize protected function Wraps file_upload_max_size().
FormBuilder::getForm public function Gets a renderable form array. Overrides FormBuilderInterface::getForm
FormBuilder::getFormId public function Determines the ID of a form. Overrides FormBuilderInterface::getFormId
FormBuilder::handleInputElement protected function Adds the #name and #value properties of an input element before rendering.
FormBuilder::prepareForm public function Prepares a structured form array. Overrides FormBuilder::prepareForm
FormBuilder::processForm public function Processes a form submission. Overrides FormBuilderInterface::processForm
FormBuilder::rebuildForm public function Constructs a new $form from the information in $form_state. Overrides FormBuilderInterface::rebuildForm
FormBuilder::redirectForm public function Redirects the user to a URL after a form has been processed. Overrides FormSubmitterInterface::redirectForm
FormBuilder::renderFormTokenPlaceholder public function Renders the form CSRF token. It's a #lazy_builder callback.
FormBuilder::renderPlaceholderFormAction public function Renders a form action URL. It's a #lazy_builder callback. Overrides FormBuilder::renderPlaceholderFormAction
FormBuilder::retrieveForm public function Retrieves the structured array that defines a given form. Overrides FormBuilderInterface::retrieveForm
FormBuilder::setCache public function Stores a form in the cache. Overrides FormCacheInterface::setCache
FormBuilder::setInvalidTokenError public function Sets a form_token error on the given form state. Overrides FormValidatorInterface::setInvalidTokenError
FormBuilder::submitForm public function Retrieves, populates, and processes a form. Overrides FormBuilderInterface::submitForm
FormBuilder::trustedCallbacks public static function Lists the trusted callbacks provided by the implementing class. Overrides TrustedCallbackInterface::trustedCallbacks
FormBuilder::validateForm public function Validates user-submitted form data in the $form_state. Overrides FormValidatorInterface::validateForm
FormBuilder::valueCallableIsSafe protected function Helper function to normalize the different callable formats.
FormBuilder::__construct public function Constructs a new FormBuilder.
FormBuilderInterface::AJAX_FORM_REQUEST constant Request key for AJAX forms that submit to the form's original route.
TrustedCallbackInterface::THROW_EXCEPTION constant Untrusted callbacks throw exceptions.
TrustedCallbackInterface::TRIGGER_SILENCED_DEPRECATION constant Untrusted callbacks trigger silenced E_USER_DEPRECATION errors.
TrustedCallbackInterface::TRIGGER_WARNING constant Untrusted callbacks trigger E_USER_WARNING errors.