[Drupal] How can we Programmatically Create user Roles in Drupal 8?

| | 1 min read

In one of my project I want to create user roles programmatically and the role should be enable and disable while module install and uninstall process. So first of all I need to create a YAML file based on the user role name with necessary definitions. The name of the YAML file should be the format user.role.sample.yml. Here sample is my user role id. To make the role enable and disable while module installation and uninstall we have to add dependency with enforced property.

Note that the YAML file should be stored in YOURMODULE/config/install folder. The definitions that I have added in the file as:

langcode: en
status: true
dependencies:
  enforced:
    module:
      - mymodule # This is the name of the module.
id: sample
label: 'Sample Role'
weight: 3
is_admin: false
permissions: {  }

After YAML file creation I have uninstalled and install 'mymodule', and found that its working fine. Hope this helps.