Tips & Tricks

This page provides useful short snippets of code to help module developers upgrade their Tripal v3 compatible modules to work with Drupal 10. This list is not comprehensive or complete, but is meant to be an aid.

tripal_set_message() and tripal_report_error()

These functions have been upgraded and thus can be used as is. However, the new way is to use a logger service. For example:

$logger = \Drupal::service('tripal.logger');
$logger->notice('Hello world');
$logger->error('Hello world');

For more detailed information see the Tripal Logger documentation.

drupal_set_message()

Changelog: https://www.drupal.org/node/2774931

use Drupal\Core\Messenger\MessengerInterface;
// if not set by constructor...
$this->messenger = \Drupal::messenger();

// Add specific type of message within classes.
$this->messenger->addMessage('Hello world', 'custom');
$this->messenger->addStatus('Hello world');
$this->messenger->addWarning('Hello world');
$this->messenger->addError('Hello world');

// In procedural code:
$messenger = \Drupal::messenger();
$messenger->addMessage('Hello world', 'custom');
$messenger->addStatus('Hello world');
$messenger->addWarning('Hello world');
$messenger->addError('Hello world');

format_date()

\Drupal::service('date.formatter')->format($time);

Loading a User Object

To load a user using a known user ID.

// Load a user with a known UID in the $uid variable.
$user = \Drupal\user\Entity\User::load($uid);

To get the current user:

$current_user = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($current_user->id());

Attaching CSS

In Drupal 10 CSS files are part of “libraries”. Libraries are groups of “assets” such as CSS, JS, or other resources needed for a particular set of pages that the module provides. Libraries are defined in the <module_name>.libraries.yml file. For information about preparing your CSS files with drupal see the page about adding css and js files to a module. Once the CSS is setup correctly, you want to add “libraries” to pages that use them. This is done by adding an ‘#attached’ element to the render array returned by a page using the following form:

'#attached' => [
  'library' => ['<module_name>/<library_name>'],
]

Replace <module_name> and <library_name> with appropriate values.