Create a Simple Next/Previous Navigation in Drupal 8
In my last post we went over the new Drupal 8 plugin system as it concerns blocks. Today, we're going to take this idea a bit further and create a simple next/previous navigation.
First things first, you're going to want to create another new file at modules/YOURMODULE/src/Plugin/Block/YOURBLOCKNAME.php
In my case, this file looks like this:
The Finished Product
(as always, this code is available on github.)
Once this file is in place, I simply navigated to admin/structure/block and placed my block in the main content region.
Changes from Drupal 7
- Object oriented code is mandatory
The big change from Drupal 7 that you probably picked up on immediately is the fact that I had to declare a new class to create this block. Admittedly, I was a little intimidated by this idea at first, but I quickly found that this style was very liberating, and gave me an obvious simple strategy for organizing my code.
- EntityFieldQuery has been replaced by Drupal::entityQuery
If you were using EntityFieldQuery to get entities out of the database in Drupal 7, this won't be much of a culture shock to you. All that's really changed here is the syntax; the core paradigm remains unchanged. So where in Drupal 7 we would have done:
In Drupal 8 we do:
All told, not such a big shift if you ask me.
- menu_get_object() has been replaced with \Drupal::request()
You're probably used to using menu_get_object in Drupal 7 to access the node being viewed. That paradigm is gone and replaced with the infinitely more sensible \Drupal::request(). I know that's a little jarring, but try and think back on the first time you heard about menu_get_object(). "Menu? No I want a node, not a menu." This new strategy is way more intuitive.
Further reading on this subject.
- $node->created has been replaced with $node->getCreatedTime()
This is part of an overall effort to replace direct access to object properties with getter and setter methods. In fact all the properties of a node must now be accessed in this manner.
- The l() function has been replaced with \Drupal::l
This one I'm not crazy about, but it's still pretty simple to do.
A few things that tripped my up here:
- Unlike its predecessor, \Drupal::l does not automatically return an aliased path. You first need to lookup your path alias with AliasManager::getAliasByPath
- The second argument in \Drupal::l is no longer a string, but instead it is an instance of the new Url class.
- The Url object you pass into \Drupal::l must be constructed Url::fromUri or Url::fromRoute.