Drupal 9: Get List Of Content Types

3rd May 2021 - 4 minutes read time

Getting a list of content types out of a Drupal 9 site is useful in a few situations. Mostly, I find that when creating a service of some kind that I will also create an administration form for that service to allow it to be restricted to certain content types. This list can be saved to configuration so that when the service is run it only effects certain content types, based on the saved configuration.

To get a an array containing a list of the content types on a Drupal site you can use the following code.

  1. $entityTypeManager = \Drupal::service('entity_type.manager');
  2.  
  3. $types = [];
  4. $contentTypes = $entityTypeManager->getStorage('node_type')->loadMultiple();
  5. foreach ($contentTypes as $contentType) {
  6. $types[$contentType->id()] = $contentType->label();
  7. }

This generates a list of content types that are currently installed on your system. This is a list of \Drupal\node\Entity\NodeType entities so we can extract the machine name of the content type using the id() method, and the human readable name of the content type using the label() method. The above code will produce something like the following on a standard install of Drupal.

  1. Array
  2. (
  3. [article] => Article
  4. [page] => Page
  5. )

You can also include this as a function in a form to generate a list of checkboxes that can be saved to configuration. If you extend from ConfigFormBase you can easily generate a form that will save a the list of content types to the system configuration. The following block of code is a form class that will print out a list of the content types as checkboxes.

  1. <?php
  2.  
  3. namespace Drupal\mymodule\Form;
  4.  
  5. use Drupal\Core\Form\ConfigFormBase;
  6. use Drupal\Core\Form\FormStateInterface;
  7. use Symfony\Component\DependencyInjection\ContainerInterface;
  8. use Drupal\Core\Entity\EntityTypeManagerInterface;
  9. use Drupal\Core\State\StateInterface;
  10.  
  11. class MyModuleSettingsForm extends ConfigFormBase {
  12.  
  13. /**
  14.   * The entity field manager.
  15.   *
  16.   * @var \Drupal\Core\Entity\EntityFieldManagerInterface
  17.   */
  18. protected $entityFieldManager;
  19.  
  20. /**
  21.   * Constructs an AutoParagraphForm object.
  22.   *
  23.   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
  24.   * The entityTypeManager.
  25.   */
  26. public function __construct(EntityTypeManagerInterface $entityTypeManager, StateInterface $state) {
  27. $this->entityTypeManager = $entityTypeManager;
  28. }
  29.  
  30. /**
  31.   * {@inheritdoc}
  32.   */
  33. public static function create(ContainerInterface $container) {
  34. return new static(
  35. $container->get('entity_type.manager')
  36. );
  37. }
  38.  
  39. /**
  40.   * {@inheritdoc}
  41.   */
  42. public function getFormId() {
  43. return 'mymodule_settings_form';
  44. }
  45.  
  46. /**
  47.   * {@inheritdoc}
  48.   */
  49. protected function getEditableConfigNames() {
  50. return ['mymodule.settings'];
  51. }
  52.  
  53. /**
  54.   * {@inheritdoc}
  55.   */
  56. public function buildForm(array $form, FormStateInterface $form_state) {
  57. $config = $this->config('mymodule.settings');
  58.  
  59. $existingContentTypeOptions = $this->getExistingContentTypes();
  60.  
  61. $form['content_types'] = [
  62. '#type' => 'checkboxes',
  63. '#title' => $this->t('Content Types'),
  64. '#options' => $existingContentTypeOptions,
  65. '#empty_option' => $this->t('- Select an existing content type -'),
  66. '#default_value' => $config->get('content_types', []),
  67. '#required' => TRUE,
  68. ];
  69.  
  70. return parent::buildForm($form, $form_state);
  71. }
  72.  
  73.  
  74. /**
  75.   * {@inheritdoc}
  76.   */
  77. public function submitForm(array &$form, FormStateInterface $form_state) {
  78. $config = $this->config('mymodule.settings');
  79.  
  80. $config->set('content_types', $form_state->getValue('content_types'))
  81. $config->save();
  82.  
  83. parent::submitForm($form, $form_state);
  84. }
  85.  
  86. /**
  87.   * Returns a list of all the content types currently installed.
  88.   *
  89.   * @return array
  90.   * An array of content types.
  91.   */
  92. public function getExistingContentTypes() {
  93. $types = [];
  94. $contentTypes = $this->entityTypeManager->getStorage('node_type')->loadMultiple();
  95. foreach ($contentTypes as $contentType) {
  96. $types[$contentType->id()] = $contentType->label();
  97. }
  98. return $types;
  99. }
  100. }

Once the form has been saved you can extract the content types array from config using something like the following.

  1. $config = \Drupal::config('mymodule.settings');
  2. $contentTypes = $config->get('content_types');

I frequently use this block of code so I thought it might come in handy for other people.

Add new comment

The content of this field is kept private and will not be shown publicly.