I am calling external API in form build function. While submitting form gets rebuild and call external API again.

How can I avoid repetitive API calls in the form's build function? I used form_state->set() but it's doesn't seem to be working.

  • You should paste your code to check how you are using set(). The idea is correct: save API response to form, and don't request it again in build function if info is already in form. – sanzante Mar 24 at 20:37

You can test whether the form is currently rebuilding using the FormStateInterface::isRebuilding method:

if (!$form_state->isRebuilding()) {
  // Contact the API
  • Not working in my case. Tried even in simple form. – Rahul Mar 12 at 11:32
  • It always works fine for me, you'll probably need to be more specific about what "not working" means for you – Clive Mar 12 at 11:51
  • 1
    @Clive, this works when you rebuild the form after submitting, but not when the form gets rebuilt while submitting. In this case you could check for user input if (empty($form_state->getUserInput())) {} – 4k4 Mar 12 at 12:45
  • @4k4 Those sound like the same thing, what's the difference? Is it just calling it in buildForm rather than submitForm? – Clive Mar 12 at 13:00
  • @Clive, a form can be built three times during one cycle, the initial form build, then before the submit handlers are called and finally after the form is submitted and a rebuild is requested. Only the last includes submitted form values and indicates $form_state->isRebuilding() correctly. – 4k4 Mar 12 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.