I am working on a simple form for searching a collection of marriage licenses. It consists of a select box where the user may choose to search last names, first names, or both, and a text field where they type the name they're searching for.
Everything is working fine so far, except that the user input is not retained after the form is submitted. For example, if I choose "Last names" and enter "Olsen", after the form is submitted the search box will be empty and the select box will revert to its default of "Both first and last names".
Here is my buildForm()
method:
public function buildForm(array $form, FormStateInterface $form_state){
// The select box.
$form['target'] = [
'#title' => $this->t('Search'),
'#type' => 'select',
'#options' => [
'both' => $this->t('Both first and last names'),
'last' => $this->t('Last names'),
'first' => $this->t('First names'),
],
'#default_value' => $form_state->getValue('target'),
];
// The search box.
$form['q'] = [
'#title' => $this->t('for'),
'#type' => 'textfield',
'#default_value' => $form_state->getValue('q'),
];
$form['actions'] = ['#type' => 'actions'];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Go'),
];
return $form;
}
As you can see, I've tried using #default_value
to set a default value by calling the form state to get whatever the user picked/entered. But alas, this does not seem to have done it.
How do I get it to display the user input in the form after submission?
submitForm()
?