class HtmxTestForm

A small form used to test HTMX dynamic forms.

Hierarchy

Expanded class hierarchy of HtmxTestForm

1 string reference to 'HtmxTestForm'
test_htmx.routing.yml in core/modules/system/tests/modules/test_htmx/test_htmx.routing.yml
core/modules/system/tests/modules/test_htmx/test_htmx.routing.yml

File

core/modules/system/tests/modules/test_htmx/src/Form/HtmxTestForm.php, line 15

Namespace

Drupal\test_htmx\Form
View source
class HtmxTestForm extends FormBase {
  
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'htmx_form_builder_test';
  }
  
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state, ?string $type = NULL, ?string $selected = NULL) {
    $type = $type ?? '';
    $selected = $selected ?? '';
    $formUrl = Url::fromRoute('<current>');
    $form['type'] = [
      '#type' => 'select',
      '#title' => 'Type',
      '#empty_value' => '',
      '#options' => [
        'a' => 'A',
        'b' => 'B',
      ],
      '#default_value' => $type,
    ];
    (new Htmx())->post($formUrl)
      ->swap('none')
      ->swapOob('true')
      ->applyTo($form['type']);
    $defaultType = $form_state->getValue('type', $type);
    $form['selected'] = [
      '#type' => 'select',
      '#title' => 'Selected',
      '#options' => $this->buildDependentOptions($defaultType),
      '#empty_value' => '',
      '#default_value' => $selected,
    ];
    (new Htmx())->post($formUrl)
      ->swap('none')
      ->swapOob('true')
      ->applyTo($form['selected']);
    $form['data'] = [
      '#title' => 'Values',
      '#type' => 'item',
      '#markup' => '',
    ];
    (new Htmx())->swapOob(TRUE)
      ->applyTo($form['data'], '#wrapper_attributes');
    $push = FALSE;
    if ($this->getTriggerElement($form_state) === 'type') {
      $form['data']['#markup'] = '';
      $push = Url::fromRoute('test_htmx.form_builder_test');
    }
    elseif ($this->getTriggerElement($form_state) === 'selected') {
      // A value is selected.
      $defaultSelection = $form_state->getValue('selected', $selected);
      // Also update the browser URL.
      $push = Url::fromRoute('test_htmx.form_builder_test', [
        'type' => $defaultType,
        'selected' => $defaultSelection,
      ]);
      if ($defaultType && $defaultSelection) {
        $form['data']['#markup'] = "Data is {$defaultType}:{$defaultSelection}";
      }
    }
    elseif ($type && $selected) {
      $form['data']['#markup'] = "Data is {$type}:{$selected}";
    }
    if ($push) {
      $htmxPost = (new Htmx())->post($push)
        ->pushUrlHeader($push);
      $htmxPost->applyTo($form['type']);
      $htmxPost->applyTo($form['selected']);
    }
    return $form;
  }
  
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) : void {
  }
  protected function buildDependentOptions(string $selected) : array {
    $options = [
      'a' => [
        1 => 'One',
        2 => 'Two',
        3 => 'Three',
      ],
      'b' => [
        4 => 'Four',
        5 => 'Five',
        6 => 'Six',
      ],
    ];
    return $options[$selected] ?? [];
  }
  protected function getTriggerElement($form_state) : string|bool {
    $input = $form_state->getUserInput();
    return !empty($input['_triggering_element_name']) ? $input['_triggering_element_name'] : FALSE;
  }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title 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 2
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 2
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. 2
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 103
FormBase::currentUser protected function Gets the current user. 2
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.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 55
HtmxTestForm::buildDependentOptions protected function
HtmxTestForm::buildForm public function Form constructor. Overrides FormInterface::buildForm
HtmxTestForm::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
HtmxTestForm::getTriggerElement protected function
HtmxTestForm::submitForm public function Form submission handler. Overrides FormInterface::submitForm
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. 25
MessengerTrait::messenger public function Gets the messenger. 25
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 2
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; 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. 3
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. 1

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.