ImageX is incredibly fortunate to have some of the best developers working in the industry on the team. Everyday our developers and sitebuilders are coming up against challenges and are finding unique solutions, coming up with creative workarounds and making discoveries, so we’d like to share with the community.

Yuriy Gerasymov - Senior Drupal Developer

Today I was fighting with a bug that was only reproducible on the hosting environment and not on my local environment.

The problem appeared to be in the Twig form template. In Drupal 7 there was drupal_render_children($form) and that should be used in the end to render all elements you haven't explicitly rendered.

Well, there is something like that too in Drupal 8, and it looks like this:

{{ form|without(

Remember to render at the end of template to avoid unexpected behaviors. In my case the form didn't handle getting values from the http request and it was throwing php notices and not validated the form (the workflow form element was missing).

Les Cordell - Drupal Developer

This might be something you’re already familiar with, or is really obvious, but I banged my head on this for quite a while and couldn’t find any documentation on it. I found a solution that worked and I’d like to share it.

The challenge: loading in block content from a block by machine name.
Let’s say you go to D8 admin and go Structure -> Block Layout -> Types. You add a new block type in there, and then go to Structure -> Block Layout -> Custom Block Library. Once you’ve added a custom block, you’ll need to add it to Structure -> Block Layout -> Block Layout in order to actually load it programmatically.

Now you can load it by block id number programmatically, which will pull in the actual block content with all of the field data. But, what if you want to load it in by machine name? For instance you want to load in a modal block via a menu route by machine name instead of using block numbers because you have 3 sites, and not all of them are Drupal site.

If you try to load in the block programmatically using the machine name, you will load a block, but it’s bundle type is block and it doesn’t contain everything you would get if you loaded the block by block id number, and you can’t get the numerical id from the block by loading with machine name.

So to load the block via machine name and get the proper block its associated to along with it’s content, you can do this:

if($block = \Drupal\block\Entity\Block::load($block_machine_name)) {
$build = $block->getPlugin()->build();
$block_content = $build['#block_content'];

Now you can load the block by the machine name, and the magic ingredient is getPlugin()->build() followed by #block_content. Here you can get the bundle type, access to all of the field and the original block ID.

Main image credit: Photo by Goran Ivos on Unsplash