Automatically add all custom blocks to fieldsets

If you use blocks like I do, this snippet might be helpful:

// site/config/config.php
'ready' => function() {
  $blockBlueprints = Dir::files(kirby()->root('blueprints') . '/blocks');
  $blockBlueprintNames = array_map(function($blockBlueprint) {
    return F::name($blockBlueprint);
  }, $blockBlueprints);

  return [
    'blocks' => [
      'fieldsets' => $blockBlueprintNames
    ]
  ];
},

TL;DR: It automatically adds all of your custom blocks to the blocks fields.

More in-depth explanation: We have to use the ready option because Kirby must be fully initialised. In there we iterate over the blocks blueprint directory and add all the filenames to the blocks.fieldsets option. This will then be the default and can be overwritten in individual blocks fields.

2 Likes

FYI: I recently added something to make sure the text block is listed first:

'ready' => function() {
  $blockBlueprints = Dir::files(kirby()->root('blueprints') . '/blocks');
  $blockBlueprintNames = array_map(function($blockBlueprint) {
    return F::name($blockBlueprint);
  }, $blockBlueprints);

  /* Move the text block to the first position */
  $blockBlueprintNames = array_values(array_filter($blockBlueprintNames, fn($value) => $value !== 'text'));
  array_unshift($blockBlueprintNames, 'text');

  return [
    'blocks' => [
      'fieldsets' => $blockBlueprintNames
    ]
  ];
}

Thank you!

Could you point us to the documentation for the second and third line?

Many thanks!
Annaluise

Could you point us to the documentation for the second and third line?

I’ll gladly take over the explanation, in the hope that @thguenther won’t mind ;-(

$blockBlueprints = Dir::files(kirby()->root('blueprints') . '/blocks');

This line gets a list of all files in the blueprints/blocks directory within the Kirby installation. It uses Kirby’s Dir::files method to read the directory contents.

$blockBlueprintNames = array_map(function($blockBlueprint) {
  return F::name($blockBlueprint);
}, $blockBlueprints);

This line processes each file found in the previous step, extracting just the name of each file (without the extension) using the F::name function. The array_map function applies this operation to all elements in the $blockBlueprints array, resulting in an array of block blueprint names.

And to add to it:

Dir::files is a method of Kirby’s Kirby\Filesystem\Dir class: Dir | Kirby CMS
F::name is a method of Kirby’s : Kirby\Filesystem\F class: F | Kirby CMS

While array_map() is a PHP function: PHP: array_map - Manual

1 Like

Note that this approach only catches block blueprints in the site/blueprints/blocks template, not those registered via the blueprints extension in plugins. For that, you would have to get

kirby()->extensions('blueprints')

And filter them by type.