Newer
Older
<?php
namespace Drupal\uw_ct_service\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
/**
* Class ServiceSearchForm.
*
* Form for searching services.
*/
class ServiceSearchForm extends FormBase {
/**
* Returns a unique string identifying the form.
*
* The returned ID should be a unique string that can be a valid PHP function
* name, since it's used in hook implementation names such as
* hook_form_FORM_ID_alter().
*
* @return string
* The unique string identifying the form.
*/
public function getFormId(): string {
return 'service_search_form';
}
/**
* Form constructor.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
* @param string|null $description
* The description for the input element.
* @param string|null $placeholder
* The placeholder string.
*
* @return array
* The form structure.
*/
public function buildForm(array $form, FormStateInterface $form_state, string $description = NULL, string $placeholder = NULL): array {
// If there is no placeholder sent, then set it to
// search all services.
if (!$placeholder) {
$placeholder = 'Search within all services';
}
// The search input.
$form['search_input'] = [
'#type' => 'textfield',
'#placeholder' => $placeholder,
'#description' => $description ?? NULL,
'#required' => TRUE,
];
// Add a submit button that handles the submission of the form.
$form['submit'] = [
'#type' => 'submit',
'#value' => '',
'#attributes' => ['aria-label' => 'search'],
];
return $form;
}
/**
* Form submission handler.
*
* @param array $form
* An associative array containing the structure of the form.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Get the values of the form state.
$values = $form_state->getValues();
// This is an internal URL.
// Add the search string.
$url .= '/search?search-input=' . $values['search_input'];
// Get a URL object.
$url = Url::fromUri($url);
// Set the form redirection URL.
$form_state->setRedirectUrl($url);
}
}