We have a need to add ‘repeatable fields’ to a form based on input provided in a textfield. Usually, we use a ‘add another’ button to keep track of the number of fields to render in the
buildForm(), and update that number in a submit callback on the button.
The functionality we want isn’t that, though. We have a need so that when somebody enters text into a textfield (other than empty), it adds an additional group of fields below it. We are allowing people to scan barcodes, and every time they scan a barcode into a textfield, we want it to create another group of fields so they can scan another item if they want to.
We attempted to use
#submit on the textfield, but #submit doesn’t appear to trigger on the textfield, as we added a print statement, as well as a
$form-state->set() in there, and attempt to print out
$form_state->get() on the form to no avail.
Since you can’t update the form_state inside of an ajax callback, we can’t figure out a way to achieve what we want to do (Add another group of fields once text is entered into a textarea).
Is there another way we can do this?
(We only allow 10 groups to be added per submission, so as a ‘workaround’ we dynamically add 10 groups in the buildForm, then use
#states to hide each one if the previous textfield doesn’t have data, but this doesn’t allow us to add in a ‘remove’ button for each textfield so the user can remove text fields they don’t want to use.)