0

Scenario:

I have a custom form whose first step is to upload a file using a managed_file field element.

Then, after this manged file is uploaded I want to rebuild the form using information from the managed file and display new form elements that should only exist after the managed file is uploaded.

I have struggled with this for days and cannot get a working solution. The first problem is that the managed_file already has an ajax callback so I can't seem to add my own to populate and/or return field elements after the file is successfully uploaded.

I've gone as far as overriding the managed_file type with a custom form field type but I can't seem to be able to return actual form elements AND an ajax response (one of the other). Code example of my override below.

In short, how can I repopulate a custom field after a managed file uploaded is completed and add new fields dependent on the file that was uploaded?

/**
 * My Managed File Element.
 *
 * @FormElement("my_managed_file")
 */
class MyManagedFile extends ManagedFile {

  /**
   * {@inheritdoc}
   */
  public static function uploadAjaxCallback(&$form, FormStateInterface &$form_state, Request $request) {


    $response = parent::uploadAjaxCallback($form, $form_state, $request);    
    
    return $response;

  }

}
3
  • Wouldn't it "just" be a matter of adding $response->addCommand(new ReplaceCommand(..., ...)); before returning?
    – Clive
    Commented Nov 23, 2020 at 19:36
  • It looks like that only replaced the HTML in the frontend. I need the actual $form['MYELEMENT'] value to be set so I can rebuild the form with its value. To clarify, I need the fields value to be available on the backend after the managed_file callback so I can rebuild the form and programmatically render element dependent on the new field's value (backend) Commented Nov 23, 2020 at 19:37
  • @quantumized, when form elements are only dumb HTML and your backend doesn't get the field values this is most times caused by form elements defined too late in form processing. See drupal.stackexchange.com/questions/251018/…
    – 4uk4
    Commented Nov 24, 2020 at 7:29

0

Your Answer

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

Browse other questions tagged or ask your own question.