I want to build kind of a search form in Drupal 8: On submit, it shall load itself again, but below the results shall rendered. And the URL shall contain the search term, so that the result page is linkable.
This is my minimal example. My current problem ist, that the submitted form value is not fed to $form_state
.
public function buildForm(array $form, FormStateInterface $form_state) {
$form_state->setMethod('get');
$query = $form_state->getValue('query');
// Unfortunately, this is empty, even after submit.
$form['query'] = array(
'#type' => 'textfield',
'#title' => $this->t('Query'),
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Search'),
);
return $form;
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$form_state->setRebuild();
$form_state->setAlwaysProcess(TRUE);
}
When I comment out $form_state->setMethod('get');
, it is working as I want: query
is readable in the rebuild form and set as default value in the text field.
But with setMethod('get');
, query
is empty and no default is set.
I thought that $form_state->setAlwaysProcess(TRUE);
makes sure the values get processed, even via GET method, as the documentation suggests. But apparently, something is missing. Any ideas, what?
setMethod
and instead do an AJAX implementation, and have the commands insert results into an HTML wrapper ready to receive them.#ajax
with properties and callbacks, in them, you can set AJAX commands. But yeah if your actual form is more complex than shown, maybe not. Perhaps$foo = \Drupal::request()->get('url_param')
?