function SearchBlockForm::buildForm

Same name in other branches
  1. 8.9.x core/modules/search/src/Form/SearchBlockForm.php \Drupal\search\Form\SearchBlockForm::buildForm()
  2. 10 core/modules/search/src/Form/SearchBlockForm.php \Drupal\search\Form\SearchBlockForm::buildForm()
  3. 11.x core/modules/search/src/Form/SearchBlockForm.php \Drupal\search\Form\SearchBlockForm::buildForm()

Overrides FormInterface::buildForm

File

core/modules/search/src/Form/SearchBlockForm.php, line 78

Class

SearchBlockForm
Builds the search form for the search block.

Namespace

Drupal\search\Form

Code

public function buildForm(array $form, FormStateInterface $form_state, $entity_id = NULL) {
    // Set up the form to submit using GET to the correct search page.
    if (!$entity_id) {
        $entity_id = $this->searchPageRepository
            ->getDefaultSearchPage();
        // SearchPageRepository::getDefaultSearchPage() depends on
        // search.settings.  The dependency needs to be added before the
        // conditional return, otherwise the block would get cached without the
        // necessary cacheability metadata in case there is no default search page
        // and would not be invalidated if that changes.
        $this->renderer
            ->addCacheableDependency($form, $this->configFactory
            ->get('search.settings'));
    }
    if (!$entity_id) {
        $form['message'] = [
            '#markup' => $this->t('Search is currently disabled'),
        ];
        return $form;
    }
    $route = 'search.view_' . $entity_id;
    $form['#action'] = Url::fromRoute($route)->toString();
    $form['#method'] = 'get';
    $form['keys'] = [
        '#type' => 'search',
        '#title' => $this->t('Search'),
        '#title_display' => 'invisible',
        '#size' => 15,
        '#default_value' => '',
        '#attributes' => [
            'title' => $this->t('Enter the terms you wish to search for.'),
        ],
    ];
    $form['actions'] = [
        '#type' => 'actions',
    ];
    $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Search'),
        // Prevent op from showing up in the query string.
'#name' => '',
    ];
    return $form;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.