0

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.

1
  • 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
    Commented Mar 24, 2019 at 20:37

1 Answer 1

1

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

if (!$form_state->isRebuilding()) {
  // Contact the API
}
9
  • Not working in my case. Tried even in simple form.
    – Rahul
    Commented Mar 12, 2019 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
    Commented Mar 12, 2019 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())) {}
    – 4uk4
    Commented Mar 12, 2019 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
    Commented Mar 12, 2019 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.
    – 4uk4
    Commented Mar 12, 2019 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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