Multiple domains in the Drupal application are a bit of a complication to handle in our code base. In this article, I am going to discuss some important concepts that we can apply when we use multiple domains supported application. Drupal application is more flexible when you go for multiple domains. Let’s say an example you need to have some business logic that will apply for all domains and some business logic may not suitable to all domain users. In that case, we have to write our logic in our custom module to respond seamlessly.
Table of Contents
How to get the current domain
We have to install a domain module and the below code will help you in that getting a current domain. So based on the current domain or current domain’s machine name you can write your functionality.
use Drupal\domain\DomainNegotiatorInterface; $loader = \Drupal::service('domain.loader'); $current_domain = $loader->loadDefaultDomain();
Get Default Domain
The below snippet will help you to get the default domain, which we have configured.
$default = \Drupal::service('entity_type.manager')->getStorage('domain')->loadDefaultDomain(); $defaultDomainPath = $default->getPath();
How do fetch all the configured domains?
In some scenarios, you may need to get all the configured domains in your Drupal application, the below single line code we can use to fetch all the domains.
$all_domains = \Drupal::service('entity_type.manager')->getStorage('domain')->loadMultipleSorted(NULL);
How to get an active domain?
The below code can be used for getting the active domain
$active_domain = \Drupal::service('domain.negotiator')->getActiveDomain();
So here I have compiled all the multiple domains related code snippet for any Drupal application which configured with multiple domain concepts. If you have any clarification please use the below comment section, that forum will help you by interacting with other comments.