Add new comment

Hi Hari,

Form API (and by extension Ajax API) is designed explicitly to work first and foremost without Javascript enabled: this is a key principle. For that, and for several other reasons (accessibility, progressive enhancement, robustness) you should also get whatever-you-want-to-do working without Javascript first, and then see how you can use Ajax to enhance it. Work out what you want to do, get the form working, and only then add Javascript to improve the experience.

Adding the markup for a new input field in Ajax is fairly trivial (as you can see, the callback can make use of arbitrary jQuery methods). But your server-side form API array must also react to the new field, so that when you submit it, Drupal will be able to make sense of the new input field (it will normally just disregard it.) You could also encounter problems with form cache, because sometimes Drupal gets form API arrays from its cache (which won't include your new element) rather than modified for Ajax. How to work around this means adding hack upon hack to get it right!

Instead of worrying about dynamically adding the field, the simplest thing would be to make the input field already present on the form, but hide it using form states until some other input field changes (e.g. a visible checkbox) and then it can appear without an Ajax call. That way people without Javascript will be able to see the field.

The official documentation for form states is pretty hard to navigate, but there's a lot of other resources for it:

I don't think it's changed much since Drupal 8 (confusingly, Drupal 8 does have a State API, which is something different!) so you should be OK with those resources.

Hope this helps, and apologies for not quite answering your original question.