<?php namespace Drupal\uw_cfg_common\Form; use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Url; use Drupal\Core\Routing\TrustedRedirectResponse; /** * Form class for the search form. */ class UwSearchForm extends FormBase { /** * {@inheritdoc} */ public function getFormId() { return 'uw_search_form'; } /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { // Set the attributes and role for the form. $form['#attributes'] = [ 'class' => ['uw-search--form'], 'role' => 'search', ]; // The search text. $form['search-input'] = [ '#type' => 'textfield', '#attributes' => [ 'class' => ['uw-input', 'uw-input--search'], ], '#id' => 'uw-search', '#placeholder' => $this->t('Search'), ]; // Get the URL for this site to be used in the options. $url = Url::fromRoute('<front>', [], ['absolute' => TRUE])->toString(); // The type of search, either all sites or this site. $form['search-type'] = [ '#type' => 'select', '#id' => 'uw-select-site', '#attributes' => [ 'class' => ['uw-select--search'] ], '#options' => [ '' => 'On all sites', 'inurl:' . $url => 'On this site', ], ]; // The submit button. $form['actions']['#type'] = 'actions'; $form['actions']['submit'] = [ '#type' => 'submit', '#attributes' => [ 'class' => [ 'button', 'button--submit', 'button--submit__form', ], ], ]; return $form; } /** * {@inheritdoc} */ public function submitForm(array &$form, FormStateInterface $form_state) { // Get the values from the form state. $values = $form_state->getValues(); // If there is search text or type, get the parameters // set for the redirect to the search. if ($values['search-input'] || $values['search-type']) { // Variable for the parameters. $parameters = ''; // If this is a site search, add it to parameters. if ($values['search-type']) { $parameters .= $values['search-type'] . ' '; } // If there is search text add it to the parameters. if ($values['search-input']) { $parameters .= $values['search-input']; } } // The URL to the uwaterloo search. $url = 'https://uwaterloo.ca/search'; // If there are parameters, encode and add to URL. if ($parameters !== '') { $url .= '/?search-input=' . urlencode($parameters); } // Redirect to the uwaterloo search. $form_state->setResponse(new TrustedRedirectResponse($url, 302)); } }