Last active
August 28, 2024 05:48
-
-
Save MatthieuScarset/d2d3bcca3cebb864108d8de2aff55979 to your computer and use it in GitHub Desktop.
Drupal - Autosubmit exposed form in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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