Published: Feb. 13, 2017 By

When planning to upgrade a module from Drupal 7 to Drupal 8, I was originally going to start out doing TDD and unit testing before I wrote any code for this module, but since I know very little about OOP practices and Drupal 8 changes, I figured it would be easier to start out with the simplest test I could think of: visiting a path and getting a 200 response code. 

In my module, an action link is added to "admin/people" in order for users to navigate to the form where they invite new users to the site. To test if the path exists and returns a 200 HTTP response, I have to create that part of the module first.

Learn By Example

I've mentioned before that my module depends on the Token module and that I would be using examples in that codebase when I need guidance...which is all the time currently :) So, I looked in that module's routing file to copy an example route. 

If you don't know anything about how Symfony's routing system works, then you should read up on Drupal's documentation for routing. To start, you need to create a ".routing.yml" file. My user_external_invite.routing.yml file started out like this:


user_external_invite.invite_users:
  path: '/admin/people/invite/invite'
  defaults:
    _controller: '\Drupal\user_external_invite\Controller\UserInviteController::inviteUsers'
    _title: 'Invite Users'
  requirements:
    _permission: 'invite users'
user_external_invite.manage_invites:
  path: '/admin/people/invite/operations'
  defaults:
    _controller: '\Drupal\user_external_invite\Controller\UserInviteController::manageInvites'
    _title: 'Manage Invites'
  requirements:
    _permission: 'invite users'
user_external_invite.settings.form:
  path: '/admin/config/people/invite'
  defaults:
    _form: '\Drupal\user_external_invite\Form\InviteSettingsForm'
    _title: 'User External Invite Settings'
  requirements:
    _permission: 'administer users'

As you can see, at the top level you start out with the route name which will be your module's machine name and the purpose of the route. I only have three routes for my module: the page where you can invite users, the page where you can manage invites that have been sent out, and the configuration page for admins. 

Adding A Controller

The part of the routing file that is most different, at least for me, is the "_controller" parameter. In Drupal 7, the "page callback" part of hook_menu() essentially acted as the controller; however, the function specified generally ended up in the same .module file making it simple to connect the two parts together.

By placing the controller file in a certain directory structure, Drupal will automatically load that class and call the method you specify. The exact structure of your file placement is kind of arbitrary, but it is common to separate different functionality into different folders. So, I have "src/Controller/" for controller classes and "src/Form" for forms. Entities, Plugins, and Event Subscribers are other examples of other types of things that might warrant their own directories; however, you can place all your files directly in the "src" directory if you were lazy and wanted to do so. Don't be lazy, though; I won't pick you to join my Drupal dodgeball team if you are.


class UserInviteController extends ControllerBase {

  public function inviteUsers() {
    return array(
      '#markup' => 'Page Content...', 
    ); 
  } 
} 

Although my controller has a lot more going on in it, in order to get a working page up and running that we can browse to I had to write an "inviteUsers" function and return something in it. After adding that code and clearing the cache, I can navigate to "admin/people/invite/invite" and see the fruits of my labor. 

Invite Users Page

 

Action Links

While adding a link to that page of the module is all fine and good, I still have no way of having users know that can get to that page since it existed as an action link in Drupal 7 on the user overview page. 

If you remember the good ole days of hook_menu(), you could define an item as a "MENU_LOCAL_TASK" with a "MENU_DEFAULT_LOCAL_TASK" item to render a page with two or more tabs on it. In Drupal 8, those tabs have been split up into files for tasks and actions. The definitions for tasks and actions are very similar; the distinction is in where you want them placed on the page. 


user_external_invite.invite_users:
  route_name: user_external_invite.invite_users
  title: 'Invite user'
  appears_on:
    - entity.user.collection

For users to see the invite page from "admin/people" as it had been placed in Drupal 7, I had to create a "user_external_invite.links.action.yml" file. In it, I provided the route that matches the "Invite user" page and told Drupal what page the action link appears on. I ended up searching the User module's files in order to get the parent route to place in the "appears_on" key.

Users Overview Page

 

Local Tasks

To add tabs for the invite management pages, I had to create another file specifically for the local tasks, "user_external_invite.links.task.yml", a.k.a tabs. 


user_external_invite.invite:
  route_name: user_external_invite.invite_users
  base_route: user_external_invite.invite_users
  title: 'Invite Users'
  weight: 1
user_external_invite.manage:
  route_name: user_external_invite.manage_invites
  base_route: user_external_invite.invite_users
  title: 'Manage Invites'
  weight: 2

Instead of having duplicate entries to define the base path and the default tab, a "base_route" key is added to define link hierarchy. This key is essentially the same as the "appears_on" key for action items. For the default tab, the "base_route" and "route_name" are the same, and for any subsequent tabs, the base route will be the default tab's route name. Once you add that code and rebuild the cache, you should see tabs show up on your module's page. 

Invite Management Page

 

Forms

The last path I need users to get to for my module is a configuration form. In Drupal 7, you could use drupal_get_form() as a special callback to load a form at a path, and in Drupal 8, the "_form" key takes over that functionality. In "InviteSettingsForm.php", I have a class that extends "ConfigFormBase" giving me some useful functionality related to getting configuration objects to manipulate. 


class InviteSettingsForm extends ConfigFormBase {

  /**
   * InviteSettingsForm constructor.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   */
  public function __construct(ConfigFactoryInterface $config_factory) {
    parent::__construct($config_factory);
  }


  /**
   * @param \Symfony\Component\DependencyInjection\ContainerInterface $container
   * @return static
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'user_external_invite_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['user_external_invite.settings'];
  }

  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('user_external_invite.settings');
    
    // Days invite valid for.
    $form['user_external_invite_days_valid_for'] = array(
      '#type' => 'textfield',
      '#title' => t('Number of days invites are valid'),
      '#description' => t("Invites are set to expire so many days after they are created. If a user hasn't accepted the invite by that time, then you will have to send a new invite to grant that user a role."),
      '#default_value' => $config->get('user_external_invite_days_valid_for'),
      '#element_validate' => array('element_validate_number'),
      '#maxlength' => 3,
    );

    // More form items...

    // Submit button.
    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Save configuration'),
    ];

    return parent::buildForm($form, $form_state);
  }

The "getFormId()" and "getEditableConfigNames()" methods are required when extending "ConfigFormBase". The form ID can be arbitrary, but I made it resemble the machine name in the routing.yml file. The editable config name should correspond to the file you would have in "config/install" for default configuration settings.

Invite Configuration Form

 

After adding that code and clearing the cache, my form shows up at the right path. However, a user would have to know the exact path of the form in order to see it until I declare a menu link pointing to the form's route.


user_external_invite.settings:
  title: 'User External Invite Settings'
  description: 'Configure roles to invite and invite message settings.'
  route_name: user_external_invite.settings.form
  parent: user.admin_index

The tricky part of adding "user_external_invite.links.menu.yml" is finding the parent route to link it to. For some reason, the "admin/config/people" route is different than all of the other routes on "admin/config" so to find out which parent route I needed to add, I used Drupal Console and the "drupal router:debug" command. When I grepped that command for config routes, every other top level section on "admin/config" had a route that started off with "system.admin_config_" while the people config section was "user.admin_index". Go figure. 

After adding that menu links file and clearing the cache, I can see the link to the config form in the people section.

Invite Config Form Menu Link

 

With those three links files and the routing file, you should be good to go setting up routing in your Drupal 8 module. Now comes the hard part of writing the code to fill out those pages you've just made links for.