You are here
Drupal 8 API tutorials
Want to learn about the Drupal 8 APIs, with worked examples? Follow my series of tutorials, covering routing, caching, entities, config and much more!
Want to hire me?
Recent blogposts
-
Altering the length of a Drupal 8 text field that contains data
Friday, July 21, 2017 - 11:31 -
A menagerie of testing: behavioural, unit, system, smoke, regression, oh my!
Friday, June 2, 2017 - 10:11 -
Including Javascript in Behat tests, all inside a headless, virtual machine
Tuesday, May 30, 2017 - 16:51
About me
I'm J-P Stacey, and I'm a freelance technical developer and software architect, working with Drupal, Javascript, Symfony, PHP and devops, with experience in project and process management and an emphasis on usability.
I live in the UK; my website is self-hosted on bigv.io; my email is hosted by Google, and that's also what I use to share files. (More info|What is this?)
Hi Hari,
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.