I followed this tutorial to create a custom Search form that takes users to the main search page with a query in the URL (meaning it uses a get method). This gives me more flexibility than using an exposed filter, so I'd like this to work. One thing that I want to do, however, is make sure that if someone searched:
<script>alert('foo')</script>
that the query in the URL would not have the tags included. Drupal has plenty of sanitization functions, so I'm not worried about that. But I can't figure out WHERE in the custom form plugin I would actually add the sanitization.
Please help! I've included the code of my plugin below:
<?php
namespace Drupal\my_custom_search\Plugin\Form;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Xss;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
class MyCustomSearchForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'site_search_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['#action'] = '/search';
$form['#method'] = 'get';
$form['#attributes']['class'][] = 'usa-search';
$form['#attributes']['class'][] = 'usa-search-big';
$form['fulltext_search'] = [
'#type' => 'search',
'#attributes' => [
'id' => array('search-field-big'),
'size' => '',
'maxlength' => '',
],
'#prefix' => '',
'#suffix' => '',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Search'),
'#button_type' => 'search',
'#attributes' => [
'class' => ['usa-search-submit-text'],
],
'#name' => '',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
}
}
UPDATE: I ended up adding 'pattern' => '[^/><\][\\\x22,;|]+',
in the attributes array, and this at least prevents submission of text with characters I don't want. I may still try to find a JS solution that works better for the user.