Skip to content

Instantly share code, notes, and snippets.

@davidjguru
Forked from MatthieuScarset/MyCustomForm.php
Created May 19, 2023 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidjguru/7f0d2b49473db1defb117b358f08e640 to your computer and use it in GitHub Desktop.
Save davidjguru/7f0d2b49473db1defb117b358f08e640 to your computer and use it in GitHub Desktop.
Drupal - Autosubmit exposed form in JS
(function () {
Drupal.behaviors.autosubmitForm = {
attach: function (context) {
once('form-autosubmit', '[data-autosubmit]', context).forEach(function (el) {
const parentForm = el.form;
// Hide submit buttons.
parentForm.querySelectorAll('input[type="submit"]').forEach(function(input) {
input.classList.add('visually-hidden');
});
// Submit form when input change.
el.addEventListener('change', function(event) {
parentForm.submit();
})
});
}
}
})(Drupal, once);
<?php
namespace Drupal\mymodule\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a custom form.
*/
class AutosubmitForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'my_custom_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['a_dropdown_list'] = [
'#type' => 'select',
'#title' => 'Options',
'#options' => [
0 => $this->t('Hello'),
1 => $this->t('Moto'),
],
'#attributes' => ['data-autosubmit' => TRUE],
];
$form['actions'] = ['#type' => 'actions'];
// This button will be hidden by JS.
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Sort'),
];
$form['#attached']['library'][] = 'mymodule/autosubmit';
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$query = $form_state->getValues();
$form_state->setRedirect('<current>', [], ['query' => $query]);
}
}
autosubmit:
js:
js/autosubmit.js: {}
dependencies:
- core/drupal
- core/once
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment