1

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.)

6
  • The basic workflow of an Ajax request is to check in the form rebuild $form_state->getTriggeringElement() and build a form with as many new form element as you like.
    – 4uk4
    Jun 8, 2021 at 19:39
  • The 'repeatable fields' angle on this feels like what Inline Entity Forms would address. These work fine with the States API and also allow you to set a min/max/unlimited number of items.
    – Gold
    Jun 8, 2021 at 20:16
  • This is a completely module based form all generated and functional inside of a buuldForm() method. There are no entities attached to the form.
    – Ex0r
    Jun 8, 2021 at 20:29
  • And as far as $form_state, Im already getting the trigger element, but I cant update the form state inside of an ajax callback so I can't rebuuld the form with the needed number of fields.
    – Ex0r
    Jun 8, 2021 at 20:30
  • You can add an ajax enabled submit button with CSS, then use JS to 'click' it on keyup (or on blur or whatever) triggering the #ajax. You can put your submit handler on the submit button.
    – Jaypan
    Jun 8, 2021 at 21:01

0

Your Answer

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

Browse other questions tagged or ask your own question.