Skip to main content

Creating and registering custom routes for creating nodes of a certain content type

Imagine the following scenario: You have a “registration” content type, for registrations to certain events, by anonymous users. You also want a custom url per event. For example:

/register-form/event1 /register-form/event2 /register-form/event3 /register-form/event4

Of course, each endpoint, will eventually create a node of the “registration” content type.

How can this setup be accomplished?

By registering custom urls.

So... Create a custom module (preferably with Drupal Console [generate:module]) with the following structure:

├── my_module.info.yml ├── my_module.module ├── my_module.routing.yml ├── src ├── Controller │ ├── MyModuleController.php └── Routing └── MyModuleRoutes.php

Now, you can create your routes in "my_module/src/Routing/MyModuleRoutes.php".

namespace Drupal\my_module\Routing; use Symfony\Component\Routing\Route; /** * Defines dynamic routes. */ class MyModuleRoutes { /** * {@inheritdoc} */ public function routes() { $events = getEventsFromDatabase(); $routes = []; foreach ($events as $key => $value) { $eventName = taxonomy_get_name_by_tid($value); $urlAlias = taxonomy_get_urlAlias_by_tid($value); $routes['my_module.' . $urlAlias] = new Route( '/register-form/' . $urlAlias, [ '_controller' => '\Drupal\my_module\Controller\MyModuleController::createRegistration', '_title' => '"' . $eventName . '" registration', ], [ '_permission' => 'access content', ] ); } return $routes; } }

Now, let's handle the controller:

namespace Drupal\my_module\Controller; use Drupal\Core\Controller\ControllerBase; class MyModuleController extends ControllerBase { /** * Provides the node submission form. * * @return array * A node submission form. */ public function createRegistration() { $node = $this->entityManager()->getStorage('node')->create([ 'type' => 'registration', ]); $form = $this->entityFormBuilder()->getForm($node); return $form; } }

We are not done yet though. The final step is to "notify" Drupal about our custom routes. We can do that be adding the following to "my_module.routing.yml".

route_callbacks: - '\Drupal\my_module\Routing\MyModuleRoutes::routes'

Now, Drupal is ready to handle our custom routes!

For more info, you can always refer to the official documentation at Drupal 8: Routing system.

Happy routing :-)

Tags

More articles