Newer
Older
<?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',
];
// Element used to open the tray for phone view.
$form['opentray'] = [
'#type' => 'checkbox',
'#title' => $this->t('<span class="uw-search--checkboxlabel--labeltext"></span>'),
'#label_classes' => [
],
'#attributes' => [
'class' => [
'uw-input',
'uw-input--checkboxform',
],
],
];
// 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' => [
'' => $this->t('On all sites'),
'inurl:' . $url => $this->t('On this site'),
],
];
// The submit button.
$form['actions']['#type'] = 'actions';
$form['actions']['submit'] = [
'#type' => 'submit',
'#attributes' => [
'class' => [
'button',
'button--submit',
'button--submit__form',
],
],
'#prefix' => '<div class="uw-search-button__wrapper">',
'#suffix' => '</div>',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Variable for the parameters.
$parameters = '';
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
// 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']) {
// 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));
}
}