Skip to content

Instantly share code, notes, and snippets.

@jonhattan
Last active November 17, 2023 15:28
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonhattan/ed4623513a32e183f96a to your computer and use it in GitHub Desktop.
Save jonhattan/ed4623513a32e183f96a to your computer and use it in GitHub Desktop.
Drupal 8 - detect if we're in an ajax request, and if building the form for the first time, or re-building within the input processing.
<?php
use Drupal\Core\Form\FormStateInterface;
function example_ajax_form_alter() {
$ajax_form_request = \Drupal::request()->query->has(FormBuilderInterface::AJAX_FORM_REQUEST);
if ($ajax_form_request) {
if (!$form_state->isProcessingInput()) {
\Drupal::logger('example')->notice('first pass');
}
else {
\Drupal::logger('example')->notice('second pass');
}
}
}
@glassdimly
Copy link

This didn't work for me. I used (which isn't drupal specific):
$is_ajax = (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');

@lonalore
Copy link

What about this?

$is_ajax = \Drupal::request()->isXmlHttpRequest();

@proteo
Copy link

proteo commented Apr 5, 2022

That worked great @lonalore, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment