Making Ajax menu links

Last updated on
24 December 2020

This page has not yet been reviewed by Menu API maintainer(s) and added to the menu.

Goal: create a menu link that, when clicked, runs a Drupal Ajax command, rather than jumping to a new page.

There are three steps:

  1. Create a menu item in your module's .menu.yml file.
  2. Create a route for the menu item in your module's .routing.yml file, pointing to a controller method.
  3. Create a controller method. The method runs on the server. It sends Ajax commands to Drupal's client-side Ajax library.

Step 1. Create a menu entry in your module's *.links.menu.yml file

Here is an example:

skilling.dogs:
  title: Dogs
  description: 'About dogs'
  route_name: skilling.dogs
  menu_name: main
  options:
    attributes:
      class:
        - use-ajax

This creates an item in the main menu. Notice the CSS class use-ajax. That is necessary.

In this example, skilling is the name of the module. It is common to use the module name as the first part of menu and route names. Replace skilling with the name of your module.

Step 2. Create a route for the menu entry

Create a route for the menu item in your .routing.yml file. The route's root key should match the route_name in the menu.yml file. In this case, it's skilling.dogs.

skilling.dogs:
  path: '/skilling/dogs'
  defaults:
    _controller: '\Drupal\skilling\Controller\DogsController::showDogInfo'
  requirements:
    _permission: 'access content'

The _controller line points to the method that will send the Ajax command.

Step 3. Create a controller method

Example:

namespace Drupal\skilling\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\AlertCommand;

class DogsController extends ControllerBase {

  public function showDogInfo() {
    $response = new AjaxResponse();
    $response->addCommand(new AlertCommand('DOGS ARE GREAT!'));
    return $response;
  }

}

The class and method name should match those used in the _controller line in the .routing.yml item.

The method first creates an AjaxResponse object. Then it adds an alert command, which will show a JavaScript alert dialog box. You can add as many Ajax commands as you like. See the Ajax API documentation for a list of available commands. Don't forget to return the response object.

The response is sent to Drupal's client-side Ajax library. It's Drupal Magic runs each command in turn.

It's often convenient to create your own Ajax commands. You can run your own JavaScript functions on data passed from the server. For example:

  public function showGoodDogs() {
    $response = new AjaxResponse();
    $response->addCommand(new ShowGoodDogsCommand(['Renata', 'Rosie',]));
    return $response;
  }

Tags

Help improve this page

Page status: No known problems

You can: