How can I display the values returned from an external API under a form?
-
02-03-2021 - |
题
I have created a custom module that pulls in data from an external API. Users select a few values on a form; submitting the form makes a call to the external API. The module then displays the data, which has been filtered by the values entered from users.
I have been able to show the returned data with \Drupal::messenger()->addMessage()
, but this doesn't seem the right method. I've found a few other suggestions, but I can't get any of them to work. They are for older Drupal versions.
I'd like to be able to display the formatted results under the form, on the same page.
How can I achieve this in Drupal 9?
解决方案
It's not much different from what done with Drupal 7; the difference is the involved classes (which weren't implemented in Drupal 7) and the used methods.
- The submission handler stores the values obtained from the external API and sets the form to be rebuilt
- The form builder verifies the values set by the submission handler are set and shows them
In the case of a class extending the FormBase
class this means:
submitForm()
calls$form_state->setValue()
to set the value obtained from the external APIsubmitForm()
calls$form_state->setRebuild()
to tell Drupal the form needs to be rebuiltbuildForm()
uses$form_state->hasValue()
to check the value has been set and$form_state->getValue()
to get that value
As for showing the returned value, it's sufficient to use a form element similar to the following one.
$form['api_value'] = [
'#type' => 'markup',
'#markup' => $api_result,
];
As side note, the $key
value passed to $form_state->setValue()
should not be a value already used for a form element. Differently, $form_state->setValue()
would set the value submitted for that form element.