I have a booking form that's built using options that are retrieved via a third party API and because of the need to have up to date information the results from the API can't be cached (at least not for very long).
The problem I'm having is I've noticed when the form is submitted Drupal is re-calling my _form function which is triggering the API calls again and I'd like to stop it doing that to try and reduce the number of API calls that are made.
Obviously if the validation fails it needs to re-draw the form and the API calls will need to be made again but I'm wondering if there's a way to stop it doing this when the form validates so I can stop it making lots of unnecessary calls to the API.
Thanks for any help.
public function FormBuilder::buildFormBuilds and processes a form for a given form ID. The form may also be retrieved from the cache if the form was built in a previous page load. The form is then passed on for processing, validation, and submission if there is proper input.
Drupal's Form API is a set of interfaces, utility classes, and conventions that when combined together allow module developers to create forms that collect, validate, and process user-submitted data. The Form API is closely related to the Render API.
You can not avoid the re-creation of the form, if the form is to be processed by Drupal. It is a central part of Drupals form processing workflow: Every form is at least build twice, once for initial output, and at least once again when the post from the client comes in. It can even be more than that, depending on what the form does afterwards, e.g. on redisplay when any validation errors occurs (Usually a cached version gets used by then, but that depends on the specific form).
What you should do is follow Simons suggestion - on the first call to your form builder function, make your API calls and store the results in $form_state['storage']['yourIdentifier']
('yourIdentifier' being some string not used by standard form processing - usually starting with your modules name). On every call to your form builder function, you check if that results are already in $form_state['storage']
. If they are, you just use those, skipping the API calls.
This will avoid the duplicate API calls, and gives you more control on how/when to do them (e.g. you can also clear those results during validation, if a special condition calls for a refetching from the external API).
Could you store/cache the return values from the API in the $form_state['storage'], so at least if _form gets called every time you can first check storage before making the API calls again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With