0
votes

I have a custom module that is successfully displaying query results when a user navigates to a particular page, by doing a query that grabs 50 records. I want to use a form to collect user input to create a more specific query.

I have the Form working, it does collect data, it does run the query, but I can't get the results to display on the same form. I've Googled many hours on this and can't find a clear answer. The form looks like:

public function buildForm(array $form, FormStateInterface $form_state){
   $form['employee_last_name'] = array(
            '#type' => 'textfield',
            '#title' => t('Last Name:'),
            '#default_value' => (isset($record['LAST_NAME'])) ? $record['LAST_NAME']:'',
            '#attributes' => array('class' => array('test')
            )
    );

When the form returns with a result, I'm trying to write to a form table, but it doesn't seem to work. Do I need to rebuild the form show the form table? I am hoping to display the results on the same page as the form fields. I am iterating on the result and putting it in the $rows variable used in the table declaration

form table:

       $form['table'] = [
                '#type' => 'table',
                '#header' => $header_table,
                '#rows' => $rows,
                '#empty' => t('No users found'),
        ];

Thanks

1
Are you wanting to use ajax to submit the form? Show your submit function. - 2pha
No, I'm literally just trying to post the results back to the form itself. The submit function is where the query happens: - Tobi
I'm doing this in the submit: $form_state = new FormState(); $form_state->setRebuild(); $form_state->set('result', 'test'); $form_state->set('result_table', $form['results_table']); $searchForm = \Drupal::formBuilder()->buildForm('Drupal\workforce_data\Form\SearchForm', $form_state); return [ 'form' => $searchForm, ]; - Tobi

1 Answers

0
votes

I've just done the following which displays a table of results above a form. The top of my buildForm function looks like this:

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['results'] = $form_state->getValue("results_table");

On the first visit to the page $form_state->getValue("results_table") has no value and so nothing is displayed. In my submitForm function I do some stuff with the form inputs and then pack the results into $form_state as follows:

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

  // do stuff with form values and put results into table rows.

  $table = [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty'  => "no values"
  ];

  $form_state->setValue("results_table", $table);

  $form_state->setRebuild(TRUE);
}

When I submit my filled form I get returned to the form view with a table of results above the form.