Whilst working on a module I found that I needed to do something that was difficult to find information for. I think part of that is because the solution is simpler than I was thinking, but it did cause me to get lost in source code and internet issues for a while.
What I needed to do was to load in a list of configuration entities that matched certain parameters. The configuration entity I was dealing with was used to manipulate the output of a form, but only if certain conditions were met first. I thought that this information might be useful to others who are looking to load configuration entities.
In this article I will show how to search for configuration entities and how to load those entities once found. I’ll be using blocks for the examples here, but the same rules will apply to any configuration entities you want to load.
Loading The Entity Query Service
What we need to do first is get the entity query service. In case it wasn’t obvious (and it wasn’t to me) you can search for configuration entities in the same way as you would any other sort of entity. If you have used entity query to find users or pages of content then this is the same mechanism. There are, however, a couple of ways to go about doing this.
The first (and simplest) way of loading entity query is to just grab the object for the configuration entity we want to load.
$entityQuery = Drupal::entityQuery('block');
Whilst using this method does allow us to search for configuration entities, it doesn’t allow us to load those entities. To do that we need to use entity_type.manager service to find the storage for the configuration entity we want to load.