This form consists of 1 textfield, and 1 ajax button. The button should
I'm trying to make it add another textfieldtext field with each click.
buildForm
only executes on page load (according to my debug) so manipulating $form with the help oftriggering_element
hasn't been an option as I would expect from D7 experience.I know the callback code is wrong. It's to communicate where I ended up and what I'm trying to accomplish.
It works for the first one, to get a total of 2 text fields. I cannot get more than 2 to appear though.
Question: How do I accomplishsuspect the dom is being updated, but not the form. So the subsequent callbacks add an element based on the original form build.
I'm not sure how to approach this in Drupal 8?. Any insight would be appreciated.
Here is my form control
<?php
...
class MyModuleForm extends FormBase {
...
public function buildForm(array $form, array &$form_state) {
$form['foo'] = array(
'#type' => 'container',
'#tree' => TRUE,
'#prefix' => '<div id="foo-replace">',
'#suffix' => '</div>'
);
$form['foo'][0] = array(
'#type' => 'textfield'
);
$form['add'] = array(
'#type' => 'submit',
'#name' => 'add',
'#value' => t('Add'),
'#ajax' => array(
'callback' => array($this, 'addMore'),
'wrapper' => 'foo-replace',
'effect' => 'fade',
),
);
return $form;
}
public function addMore(array $form, array &$form_state) {
$form['foo'][] = array(
'#type' => 'textfield'
);
return $form['foo'];
}
}