I'm building a custom form in Drupal 9, which has some ajax callbacks.
During the buildForm
I need to load some extra data via a rest call to an external service, which then I put inside a private_tempstore
variable.
I'd like to avoid to call the rest end-point during the ajax callbacks, and rely on the stored variable.
However, I can't find a way to differentiate between the "load page" case and the "ajax case". Is it possible?
I've found this answer that seems to generally work:
// Example for brevity only, inject the request_stack service and call // getCurrentRequest() on it to get the request object if possible. $request = \Drupal::request(); $is_ajax = $request->isXmlHttpRequest();
But I'd like to know if there's some helper\solution using the form API.
buildForm
has access toFormStateInterface $form_state
, what's wrong with$form_state
?buildForm
the data I need is get from the rest endpoint, it is not inside the$form_state
. I then store that data inside thetempstore
(but I could also use$form_state->setTemporaryValue()
. During the following ajax callbacks the data could be thus accessed via$form_state
, but I obviously need to differentiate between the first case and the following ones.function buildForm() { if (!$form_state->get('some_helper_var') { $tempStore = load_external_stuff(); $form_state->set('some_helper_var', TRUE); } $form['field_foo']['default_value'] = $form_state->get('field_foo') ?? $tempStore->get('foo')); }