How to check that module installed in Drupal 9?
if (\Drupal::service('module_handler')->moduleExists('locale')) {
// your code here
}
if (\Drupal::service('module_handler')->moduleExists('locale')) {
// your code here
}
Let's imagine we don't want to have any restrictions for our route. For this we can set _access requirement to TRUE.
your_module.route_name:
path: '/your_path'
defaults:
_controller: 'Drupal\your_module\Controller\YourController::yourMethod'
requirements:
_access: 'TRUE'
\Drupal::currentUser()->hasRole('administrator')
\Drupal::currentUser()->hasPermission('permission name');
When we use autocomplete field, the submitted value will look something like this "Title of the entity (10)". To extract the current entity id from this string we can use helper function extractEntityIdFromAutocompleteInput from EntityAutocomplete
$autocomplete_data = 'Title of the entity (10)';
$entity_id = EntityAutocomplete::extractEntityIdFromAutocompleteInput($autocomplete_data);
To solve this issue we can use a small, but a very useful module Route condition. This module provides condition plugin, which will display the block based on routes. Basically it works the same way as Pages condition plugin. So, I believe you will not find any issues configure it.
Let's imagine we have a node with field category and we want to create a link in the view and pass a category in the request ?field_category=1. Unfortunately, it will not like this by default. Fortunately, we have a solution! We need a module prepopulated and pass a parameter a special way:
1) For entity reference fields
http://yourdoamain.com/node/add/page?edit[field_category][widget][0][target_id]=1
2) Normal fields
http://yourdoamain.com/node/add/page?edit[field_body][widget][0][value]=Something
If you have a basic path we can get route using router.no_access_checks service. Keep in my you have to have a leading slash
$router = \Drupal::service('router.no_access_checks');
$result = $router->match('/node/2');
In case you have URL object we can get route from it like this
$router = \Drupal::service('router.no_access_checks');
$result = $router->match($url->toString());
To get route by name in Drupal 9 we need to use router.route_provider service.
$route_provider = \Drupal::service('router.route_provider');
$route = $route_provider->getRouteByName('user.page');
To check this we need to use router.admin_context service
if (\Drupal::service('router.admin_context')->isAdminRoute()) {
// Do something here.
}
We also can check a specific route
$route_provider = \Drupal::service('router.route_provider');
$route = $route_provider->getRouteByName('user.page');
if (\Drupal::service('router.admin_context')->isAdminRoute($route)) {
// Do something here.
}
In some cases we want to load a configuration file from optional / install folders. For example to compare it with active config and apply new changes.
To load a configuration from install folder user the next code snippet.
use Drupal\Core\Config\ExtensionInstallStorage;
$field_storage = 'field.storage.group_content.grequest_status';
$install_storage = new ExtensionInstallStorage(
\Drupal::service('config.storage'),
InstallStorage::CONFIG_INSTALL_DIRECTORY,
InstallStorage::DEFAULT_COLLECTION,
TRUE,
NULL
);
From optional folder
use Drupal\Core\Config\ExtensionInstallStorage;
$name = 'views.view.group_pending_members';
$optional_storage = new ExtensionInstallStorage(
\Drupal::service('config.storage'),
InstallStorage::CONFIG_OPTIONAL_DIRECTORY,
InstallStorage::DEFAULT_COLLECTION,
TRUE,
NULL
);
and schema configuration
use Drupal\Core\Config\ExtensionInstallStorage;
$name = 'views.view.group_pending_members';
$optional_storage = new ExtensionInstallStorage(
\Drupal::service('config.storage'),
InstallStorage::CONFIG_SCHEMA_DIRECTORY,
InstallStorage::DEFAULT_COLLECTION,
TRUE,
NULL
);
For this we need implement user_login hook and then we check the last access field.
use Drupal\user\Entity\User;
/**
* Implements hook_user_login().
*/
function mymodule_user_login(User $user) {
if (empty($user->getLastAccessedTime())) {
// Do something here.
}
}
Let's imagine we want to send a user to custom route after login in our example to user edit form. How do we do it ?
We need to implement user_login hook
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\user\Entity\User;
/**
* Implements hook_user_login().
*/
function mymodule_user_login(User $user) {
$url = Url::fromRoute('entity.user.edit_form', [
'user' => $user->id(),
]);
$redirect = new RedirectResponse($url->toString());
$redirect->send();
}
We need to user service "messenger" service, which will store the message in the session and fetch during the next request.
# 1. Standard way to get messenger service, in case you want to pass it using dependency injection.
$messenger = \Drupal::service("messenger");
# 2. Fast way to use helper function.
$messenger = \Drupal::messenger();
Also in the form object or controller we don't have include it using dependency injection. We can us directly
$messenger = $this->messenger();
1. Add message. Allows to send a message of any type, the second parameter accepts the type
$meesenger->addMessage(t('Your message.'), MessengerInterface::TYPE_WARNING);
But in most of the cases it is better to use directly specific method
2. Add status
$messenger->addStatus(t('Your message'));
3. Add warning
$messenger->addWarning(t('Your message'));
4. Add error
$messenger->addError(t('Your message'));
It is quite easy to do instead of MigrateExecutable class, we need to use MigrateBatchExecutable and instead of import we need to use batchImport
use Drupal\migrate_tools\MigrateExecutable;
$migration = \Drupal::service('plugin.manager.migration')->createInstance($migration_id);
if (!empty($migration)) {
// here we can set additional options like limit, update or force the import.
$options = [
'limit' => 0,
'update' => 1,
'force' => 1,
];
$executable = new MigrateBatchExecutable($migration, new MigrateMessage(), $options);
$executable->batchImport();
}