Drupal - How do I change the default value of a field with AJAX?

Method 1 setting #value does indeed make it impossible for the user to input data.

So the method 2 setting #default_value is I think still the best approach. As the old trick from D7, unsetting the value in $form_state, doesn't work anymore, you can try this one:

Create the field in a subkey, which is incremented for each request. Set the property #tree on the first level of the field, so you get back the field value as array [$key => $value]:

$form['wrapper']['options']['field1']['#tree'] = TRUE;

if ($form_state->hasValue('field1')) {
  $key = key($form_state->getValue('field1'));
  $value_field1 = current($form_state->getValue('field1')); 
  $key++;
}
else {
  $key = '0';
  $value_field1 = NULL;
}

// insert logic to determine new field value
// but check, if there is user input in $value_field1, that you don't want to overwrite

$form['wrapper']['options']['field1'][$key] = [
  '#type' => 'textfield',
  '#title' => 'Text 1',
  '#default_value' => $value_field1,
];

Tags:

Forms

8