Skip to content

Instantly share code, notes, and snippets.

@kartagis
Forked from MatthieuScarset/MyCustomForm.php
Created May 29, 2023 14:41
Show Gist options
  • Save kartagis/5eeb92c76cd40c3bdf06a7b893e14e4c to your computer and use it in GitHub Desktop.
Save kartagis/5eeb92c76cd40c3bdf06a7b893e14e4c 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