How to enable (install) a module programmatically in Drupal 8
While maintaining a website, there are quite a few situations in which you might want to enable a module programmatically. In this post, we will see how do do that in Drupal 8.
Why would you enable a module programatically?
In a Drupal agency, we came across various scenarios in which enabling modules progarmatically is the best solution. Primarily this is a result of using CI do manage the development pipeline, but there are also particular other situations:
- Perhaps you are supporting a very busy Drupal business website which cannot have too much downtime. The best approach to deploying in such case is to prepare all changes in code and pushing them to production automatically.
- It might be that you are working on a very big corporate website and do not have access to a production environment. If your task requires a new module, the only way to deliver it is by installing via code.
Every drupal developer will benefit from being able to install a module from code.
Installing
A big change in Drupal 8 is that you can no longer enable and disable modules. You can only install and uninstall. The difference is paramount.
In Drupal 7 if you disabled a module and then enabled it back, you retained the modules settings all data stored by that module. This is not longer the case with Drupal 8. Uninstalling means completely removing all data and settings added to the module when it was installed. So please, be careful :)
How to install a module programmatically? Check below:
Lets install Admin Toolbar. A nice handy module extending the Drupal default toolbar.
\Drupal::service('module_installer')->install(['admin_toolbar']);