Blogs

EMAIL: info@example.com

#! code: Drupal 9: Creating A GET Form

I’ve been building Drupal forms for a number of years so I’m quite familiar with to putting together a Drupal form using the FormBase class and the form API. When I attempted to create a GET form this week I realised that there is actually quite a bit to think about. All forms are build using GET requests, it’s the submission that I am specifically talking about. By default, forms in Drupal use POST requests to submit their data, and although it is possible to convert a form to use GET to submit data, it isn’t well documented.

There are a couple of GET forms already available in Drupal. If you look at the Views filter form or the Search form they both process submissions through a GET request. These forms tend to use a combination of a form, a hook and a controller to manage their rendering and results. What I wanted was an example of a GET form that was more self contained inside a Drupal form object.

To set a form to submit using the GET method you use the setMethod() function of the form state.

$form_state->setMethod('GET');

This is by no means the whole story as there are a few other things to consider. Everything from how you get data from the form input to considerations of the URL structure is important. In fact, I would say that creating GET forms requires a slightly different way of looking at forms than the normal POST request forms.

As an example of how to set up GET forms, I will take a simple POST form and turn into a GET form, detailing the steps involved. The following code is a standard Drupal form that uses a POST request and prints out the input field as a message.

Read more.


Go to Source
Author: