Drupal 8: How to Change The Contact Page Title (Contact Form Core Module)

a.abuzakham

Many devs in Drupal agencies mentioned this difficulty in forums. The Drupal 7 menu system revolved around hook_menu(), which provided associations between paths and callback functions (controllers) and also served as a central place to provide menu items in different menus (mostly in the administration menu) associated with the paths, as well as providing tabs and action links on pages and contextual links for different paths. It also did access checking, entity loading, and many other functions - of course, it is a lot to handle for just one system.

That's why in Drupal 8 these areas of functionality are now separated into different systems. The association of a path with a controller, coupled with parameter upcasting and access checking, is now handled in the routing system. This system serves as a basis for path access on a Drupal 8 site. The Drupal 8 menu system is now a collection of different APIs for menu items defined by modules as well as local tasks, actions, and contextual links.

Below you'll find two easy steps that will allow you to alter contact form routes:

 

Step 1: 

Create a custom module. In your custom module, create a new class that extends RouteSubscriberBase in src/Routing/RouteSubscriber.php file in your module to alter the contact form routes. 

<?php
/**
 * @file
 * Contains \Drupal\YOUR_CUSTOM_MODULE\Routing\RouteSubscriber.
 */

namespace Drupal\YOUR_CUSTOM_MODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {
  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('contact.site_page')) {
      $route->setDefault('_title', 'Contact us');
    }
  }
}

 

Step 2: 

The class must be registered as an event subscriber service. Use a YOUR_CUSTOM_MODULE.services.yml file in your module.

services:
  YOUR_CUSTOM_MODULE.route_subscriber:
    class: Drupal\YOUR_CUSTOM_MODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

 

That's basically it. Should you have any concerns or difficulties applying our recommendations on your website, let us know, and we will be happy to provide you with an individual response to your comment. Also feel free to share this article if you find it helpful!