Skip to content

Instantly share code, notes, and snippets.

@MatthieuScarset
Last active August 28, 2024 05:48
Show Gist options
  • Save MatthieuScarset/d2d3bcca3cebb864108d8de2aff55979 to your computer and use it in GitHub Desktop.
Save MatthieuScarset/d2d3bcca3cebb864108d8de2aff55979 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