I have a custom multi-step Ajax form. On the second step, I have defined a managed_file
field where users can upload several attachments:
public function buildForm(array $form, FormStateInterface $form_state)
{
$form['#tree'] = TRUE;
...
$step = !empty($form_state->getValue('step')) ? $form_state->getValue('step') : 1;
$form['step'] = [
'#type' => 'value',
'#value' => $step,
];
// Steps previous to current one
$steps = [1, 2, 3];
foreach ($steps as $prev_step) {
if ($prev_step < $step && $formState->hasValue('step' . $prev_step)) {
$form['step'. $prev_step] = [
'#type' => 'value',
'#value' => $formState->getValue('step'. $prev_step),
];
}
}
// Current step
switch ($step) {
...
case 2:
$form['step' . $step] = [
'#type' => 'fieldset',
'#title' => $this->t('Step @number: Compose Emails', [
'@number' => $step
]),
];
...
$form['step' . $step]['test_file'] = [
'#type' => 'managed_file',
'#upload_location' => 'public://attachments/',
'#multiple' => TRUE,
'#description' => 'This is a description',
'#upload_validators' => [
'file_validate_extensions' => [],
'file_validate_size' => array(25600000)
],
'#default_value' => $form_state->hasValue(["step$step", 'test_file']) ? $form_state->getValue(["step$step", 'test_file']) : []
];
...
}
...
}
However, upon uploading the file, the uploadAjaxCallback
of Drupal\file\Element\ManagedFile
is not able to find my nested step2
array in $form
:
# \Drupal\file\Element\ManagedFile::uploadAjaxCallback, line 190
// Before calling getValue, $form does not have key 'step2', only 'step1'
$form = NestedArray::getValue($form, $form_parents);
// $form is now NULL!
Consequently, nothing is displayed in my form, and the file upload fails.
Am I doing something wrong here?