I have a simple form where users can set the number of fields they need. Users may need 100+ fields so I am not using ajax "add more" options.
With the below code, everything works (Even though you have to save the form twice, once to add the fields, twice to save the data), but I get an Undefined offset notice Notice: Undefined offset: n
anytime I increase the field count and save the form.
As I'm not sure a better way to ask this question...
1) I know the code below is not perfect UX (having to save a form twice), does Drupal offer any API advantages to my approach I am not aware of?
2) Is there a way to handle/suppress these notices?
public function buildForm(array $form, FormStateInterface $form_state) {
$config = $this->config('MYMODULE.settings');
$form['#tree'] = TRUE;
$form['fieldset'] = [
'#type' => 'fieldset',
];
$form['fieldset']['field_number'] = [
'#type' => 'textfield',
'#default_value' => $config->get('field_number') ?: 1,
];
for ($i = 0; $i < $config->get('field_number'); $i++) {
$form['fieldset']['field'][$i] = [
'#type' => 'textfield',
'#default_value' => $config->get('field')[$i] ?: '',
];
}
return parent::buildForm($form, $form_state);
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$this->configFactory->getEditable('MYMODULE.settings')
->set('field_number', $values['fieldset']['field_number'])
->set('field', $values['fieldset']['field'])
->save();
parent::submitForm($form, $form_state);
}
'#default_value' => $config->get('field')[$i]
. So if you have 1 field and add 100, you get 100 notices of undefined offset. Not sure how to get an un-submitted form field value into $form_state as form fields don't have any type of'#onblur'
or anything as far as I know. Hoping to add 100+/- fields in one click.isset()
. For dynamic forms in general, try to not submit and save the values until the end. Rebuild the form instead, then check inbuildForm()
the value offield_number
in$form_state
and build the dynamic form elements accordingly.$nojs
in the ajax examples you get dynamic forms rebuilding without#ajax
: cgit.drupalcode.org/examples/tree/ajax_example/src/Form$form_state->setRebuild(TRUE)
via a submit form element, I am not sure how to get the altered/activefield
value, not the[#default_value]
.