I wanted today to make clean search page, without any additionals options than input text field. As you can easily hide advanced search from guests by using permissions, there was still little url to the search help page. Of course you can hide it from css if you are lazy, but let's remove it for good.
First, I wanted to check where this link came from and how is attached. Form is generated in this class:
// /core/modules/search/src/Form/SearchPageForm.php
[...]
$form['help_link'] = [
'#type' => 'link',
'#url' => new Url('search.help_' . $this->entity->id()),
'#title' => $this->t('Search help'),
'#options' => ['attributes' => ['class' => 'search-help-link']],
];
There is no option to turn this off or I didn't found any. It's just added there and exist, and makes me mad.
Let's remove this! In your theme, add this function, and replace scriptun with your theme name:
function scriptun_form_alter(&$form, $form_state, $form_id) {
switch ($form_id){
case 'search_form':
unset($form['help_link']);
break;
}
}
And that is all you need to simply hide it. You can use regular if condition there, but I always put switch in form_alter hook, to be prepared for other forms.
Removing of search help page
Link was removed and it's ok, but if you go directly to /search/node/help page still works! Let's remove this! :)
In your module, create yaml file for services if you don't have yet:
# /modules/scriptun_module/scriptun_module.services.yml
services:
scriptun_module.route_subscriber:
class: Drupal\scriptun_module\Routing\RouteSubscriber
tags:
- { name: event_subscriber }
scriptun_module it's just example name, you can change whole line to whatever you want. Most important is class, where you need to add your route subscriber full class name and tag, where you attach event_subscriber tag.
So we have new service declared and it point to RouteSubscriber class, create it:
<?php
// /modules/scriptun_module/src/Routing/RouteSubscriber.php
namespace Drupal\scriptun_module\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Listens to the dynamic route events.
*/
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
if ($collection->get('search.help_node_search')) {
$collection->remove('search.help_node_search');
}
}
}
Remember to change scriptun_module name in namespace, according to your module machine name.
Clear all caches and if you go to /search/node/help you should see a nice 404 error.
Remember, that if you don't remove this link also in your theme with form_alter, you may see a critical error with message:
Go back to the beginning of this page, and add correct form_alter hook to your theme functions.
Of course this is my way of removing search help page. If you have any other ideas let me know in the comments.
Add new comment
Comments
Helder
Thank you very much. It worked nicely.