Can you save state in the $form_state variable that remains when the form is rebuilt? I have a form with a nested subform that has an ajax submit button in it. The subform is built inside a form_alter and attached to the form. The submit buttons #name is made unique by using a UUID generator.
When I press the ajax submit button, Drupal steps through its form builder steps rebuilding the form. Because of this, the same code in the form_alter is called rebuilding the same subform. The problem is that when it is rebuilt, the submit button gets a brand new #name via the UUID generator. As such, Drupal cannot match the _triggering_element to a #name, and the ajax fails.
One solution I thought to try was to attach the #name to $form_state storage when the form is first built hoping that it would be available when the form is rebuilt. For e.g. in the same form_alter I execute:
      $input = $form_state-&gt;getUserInput();
      if($input){
        //This only runs when the form is being rebuilt
      }

And I may be able to grab the correct #name out of $form_state storage and set it so Drupal can correctly match and find the right ajax callbacks.
Is something like this possible? Is there a better way to handle this?
You only need #name if the form array keys don't provide a unique path for form_state. I agree with @Jaypan, I too found setting #name never really necessary, it seems to be more reliable to define a unique key to the lowest level of the form element if you have issues with Ajax not finding the form element. In either case, #name or form key, it has to be predictable, derived from data which doesn't change between form builds, for example a field delta.
The form object and $form_state are not cached when a form is rendered, only after submitting the first Ajax request. So it doesn't help to store data in $form_state you want to use to rebuild $form.