No response from $block->isHidden()?

Hello,

I am trying to return all blocks, even those set to hidden, but it seems that toBlocks() only returns visible blocks. Is there a way to return all blocks regardless of whether or not they are hidden in the panel?

Thank you,

1 Like

The toBlocks() method filters out the hidden blocks, so you would need a custom field method that does the same as toBlocks() but without filtering the hidden ones.

I’d like to do this too (get hidden blocks), but when I try to do a custom field method with a new version of ->toBlocks, I get an “Invalid blocks data for “blocks” field on parent” error thrown (for line 19 in the screenshot).

I just copied the toBlocks method from Kirby/config/methods.php to site/plugins/field-methods/index.php, and changed the method name to toHiddenBlocks.

Indeed, the $field passed to the default ->toBlocks() method looks like this…

Kirby\Cms\Field Object
(
    [blocks] => [
    {
        "content": {
            "text": "...

… whereas the $field passed to my custom field plugin looks likes this…

[ {
   "content": { 
      "text": "...

and the only difference in the template is

$page->blocks()->toBlocks
$page->blocks()->toHiddenBlocks

Finally, when I force the Field data type in the argument, I get this error: `Kirby\Filesystem\F::{closure}(): Argument #1 ($field) must be of type Field, Kirby\Cms\Field given, called in …/code/public/kirby/src/Cms/Field.php on line 78’. It’s like two different data types are being passed to functions saved in different locations, but the sending data is the same.

This returns all blocks, if you only want the hidden ones, you have to filter again, just the other way round.

<?php

use Kirby\Cms\App as Kirby;
use Kirby\Cms\Blocks;
use Kirby\Cms\Field;

Kirby::plugin('cookbook/field-methods', [
    'fieldMethods' => [
        'toHiddenBlocks' => function (Field $field) {
            try {
                $blocks = Blocks::factory(Blocks::parse($field->value()), [
                    'parent' => $field->parent(),
                ]);

                return $blocks;
            } catch (Throwable $e) {
                if ($field->parent() === null) {
                    $message = 'Invalid blocks data for "' . $field->key() . '" field';
                } else {
                    $message = 'Invalid blocks data for "' . $field->key() . '" field on parent "' . $field->parent()->title() . '"';
                }

                throw new InvalidArgumentException($message);
            }
        },
    ],
]);
1 Like