1

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.

1 Answer 1

5

Drupal's mantra is to sanitise upon output, not input. See Writing secure code for Drupal 8 for more information.

So there's no need to sanitise upon submission, just make sure that if you're rendering that value anywhere, it's done in a secure manner (as explained in the docs above).

If you decide that you still need the solution you've outlined, it's going to have to be implemented in JavaScript. Your form method is GET so the browser handles the input -> URL conversion, not Drupal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.