0

I have a form that I'm trying to build that is semantically identical to billions of others on the net:

  1. First GET request returns an empty form with no results displayed.
  2. Submitting the form POSTs all data to the same page.
  3. Server collects information from the database/other service based upon the submitted data.
  4. Final response contains the same form with the fields still filled out, and a results table at the bottom.

But implementing this classic workflow seems to be impossible in Drupal 8.

I have been reading outdated documentation on the D7 Form API for what seems like forever, and have decided that it's probably best for me to implement a form that submits via AJAX and adds the results table to the page dynamically. But I'd like to know whether this would be the best approach, as well as other methods of doing what I want whether they're "better" or not.

I'd love to give you guys an idea of what I've tried, but the appropriate project files, as well as my brain, are so scrambled right now that I can't figure out what to show. So just some general pointers in the right direction would be very much appreciated.

2
  • This is not at all impossible in D8, although I grant you it's far from intuitive. My recent answer to a similar question might be a nod in the right direction. Commented Mar 22, 2020 at 23:42
  • @stevekeiretsu LOL yes I didn't really mean impossible; just far from intuitive as you said, and poorly-documented to boot. Thanks for the answer though; +10 for you sir! :D
    – Kenny83
    Commented Mar 23, 2020 at 0:10

1 Answer 1

0

Expanding that comment into a minimalist example code answer:

public function submitForm(array &$form, FormStateInterface $form_state) {

  // get the submitted data
  $foo = $form_state->getValue('foo');

  // call any other service to process your form submission values
  // (you can replace this with dependency injection of course)
  $bar = \Drupal::service('other.service')->baz($foo);

  // add results element to the $form

  $form['results'] = [
    '#type' => 'table', // or markup, or whatever you want to build your results
     // could also do #theme for a custom theme hook.  
     // Use $foo, $bar etc however you want here
  ];

  // rebuild the form with your newly added results element,
  // and prevent drupal from redirecting to a separate GET page, 
  // so that the populated form remains visible above the results.
  $form_state->setRebuild(TRUE);
  $form_state->disableRedirect(TRUE);
}

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.