3

I created a module for searching values from external databases. My controller creates a form and send it to the custom twig page of my module.

The controller method that creates the form and send the data to the twig template looks like:

 public function customSearchPage($query, $results)
    {
         $searchForm = \Drupal::formBuilder()->getForm('Drupal\movies\Form\SearchForm');

        $searchForm['searchQuery']['#value'] = $query;

        return [ 
            '#theme' => 'insert_movie_page',
            '#form' => $searchForm,
            '#query' => $query,
            '#results' => $results,
        ];
    }

Now I created a Form using the Drupal 8 Form API. The submitForm method will send the inserted data to a compute class and gets a resultset back (array with multiple model objects). Now I need to send the resultset back to the twig template to show the results to the users. How can I achieve this behaviour?

SubmitForm method looks like:

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

      $search = $form_state->getValue('searchQuery');

      $SearchController = new SearchController;
      $results = $SearchController->searchMovies($search);
  }
5

In submit you have two choices.

Rebuild

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

  $form_state->setRebuild();
}

The form and the twig template the form is wrapped in will be rebuilt and you can display the result.

This is a great question from @AdrianCidAlmaguer to demonstrate how this works with a basic example how to display the sum of two numbers: How to show a string once you submit a form in a page reloading the page?

Redirect

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

  $form_state->setRedirect($route_name, $route_parameters, $options);
}

You redirect to a new page and can display the result there.

  • How to send the array with objects using the redirect way? I don't want to markup the result already in the form because of the complexity and is better to place that in twig. – JimmyD Jan 8 '17 at 16:12
  • 1
    For simple cases you can add query parameters to the route. For complex cases you use most times a session. - But for anonymous users the rebuild is far more efficient and this is probably the better approach, because drupal has a temp store for the form data and you can build very complex things by just rebuilding a form again and again. – 4k4 Jan 8 '17 at 16:18
  • The page is only visible for authenticated users. So I can use session vars for this. Tnx – JimmyD Jan 8 '17 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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