Use previously-submitted values as default values in a GET-method form I have a custom form defined by the class below :

class MyForm extends FormBase {

    /**
     * @see \Drupal\Core\Form\FormInterface::getFormId()
     */
    public function getFormId(){
        return 'my_form_id';
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::buildForm()
     */
    public function buildForm( array $form, FormStateInterface $form_state ){       
        $form['my_textfield'] = array(
            '#type' =&gt; 'textfield',
            '#title' =&gt; t('My textfield'),
            '#default_value' =&gt; 'I want the current value here !',
            '#description' =&gt; t('Description of my textfield.'),
            '#required' =&gt; true
        );

        return $form;
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::validateForm()
     */
    public function validateForm( array &amp;$form, FormStateInterface $form_state ){
        // Not implemented yet...
    }

    /**
     * @see \Drupal\Core\Form\FormInterface::submitForm()
     */
    public function submitForm( array &amp;$form, FormStateInterface $form_state ){
        // Not implemented yet...
    }

}


The form is then built in my page controller, using \Drupal::formBuilder()-&gt;getForm(). It overrides the form's #method attribute to GET because I want the field state to be present in the URL.

I'm looking for a correct Drupal-friendly way to assign the #default_value of my fields with the previously submitted state of the form.

Edit:

If I use a classic POST-method form and I add $form_state-&gt;setRebuild(); in ::submitForm(), I can get my values in ::buildForm() using $form_state-&gt;getValues(). And the form is automatically rebuilt with the previously submitted values, without having to assign the default values programmatically...



Could-be-related posts


Access data from previously submitted values in buildForm in FormBase plugin
GET method form is not processed
You will have to set query parameters on submit and then you can fetch them and use as default values.


1] Redirect on submit

$form_state-&gt;setRedirect($route_name, $route_parameters, $options);


2] Fetch query parameters

$params = \Drupal::request()-&gt;query-&gt;all();