0

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?

1 Answer 1

0

Try to store the step in $form_state:

$step = $form_state->has('step') ? $form_state->get('step') : 1;
$form_state->set('step', $step);
1
  • Still no luck. Even adding a managed_field field on the second step of the Wizard defined in the Examples for Developers module fails. This looks like a Drupal core bug...
    – tomurillo
    Commented Jun 30, 2022 at 10:36

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.