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 bool $use_placeholder
* Flag to user placeholder.
* @param string|null $placeholder
* The placeholder string.
* @param string|null $description
* The description for the input element.
* @param string|null $uuid
* The unique id.
*
* @return array
* The form structure.
*/
public function buildForm(
array $form,
FormStateInterface $form_state,
bool $use_placeholder = TRUE,
string $placeholder = NULL,
string $description = NULL,
string $uuid = NULL
): array {
// If there is no placeholder sent, then set it to
// search all services.
if ($use_placeholder && $placeholder == NULL) {
$placeholder = 'Search within all services';
}
// Add the unique id.
Eric Bremner
committed
$form['#attributes']['id'] = 'service-search-form-' . $uuid;
// The search input.
$form['search_input'] = [
'#type' => 'textfield',
'#placeholder' => $use_placeholder ? $placeholder : NULL,
'#description' => $description ?? NULL,
'#required' => TRUE,
'#attributes' => [
'id' => 'edit-search-input-' . $uuid,
],
];
// 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.
$url = 'internal:/services';
// 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);
}
}