Do you want to know how to Drupal?

Let's Drupal

Posts


How to provide full access to route in Drupal?

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'

 




How to extract entity id from autocomplete string in Drupal?

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);

 


How to display / place a block based on route in Drupal?

By default Drupal provides and option to set visibility of block based on path, but quite often it is not what actually want.

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.
 


How prepopulate values on a form from request in Drupal?

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

How to get a route by URI in Drupal?

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());


How to check if the current page using admin theme in Drupal?

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.
}

 


How to load a configuration file from module in Drupal 9?

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
);

 


How to detect the very first login of the user in Drupal 9?

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.
  }
}

 


How to redirect a user after login in Drupal 9?

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();
}


 


How to show a message in Drupal 9?

Sometimes we need to inform a user about a result of some operations. For example we have submitted the form and we want to show a success message or an error

We need to user service "messenger" service, which will store the message in the session and fetch during the next request.

Get instance of messenger service

# 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();

Methods

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'));

How to run migration programmatically as a batch operations in Drupal 9?

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();
}