Access field in block for json encoding

Hello!

I’m trying to create a content representation for all subpages on a page. All subpages have only one block that could either be an image block or a video block. I don’t need all the information in the block only the url to the file/video url. But I don’t understand how I would access that.

This is what I thought would work to access the image url (no page has a video block atm)

<?php

$data = $site->children()->find('members')->children()->listed()->children()->listed();
$json = [];

foreach($data as $article) {
    $block    = $article->work()->toBlocks();
    $src      = null;
    
    if ($image  = $block->image()->toFile()) {
        $src    = $image;
    }

  $json['data'][] = array(
    'url'           => (string)$article->url(),
    'parentUrl'     => (string)$article->parent()->url(),
    'parentTitle'   => (string)$article->parent()->title(),
    'title'         => (string)$article->title(),
    'year'          => (string)$article->year(),
    'src'           => (string)$src
  );

}

echo json_encode($json);

I understand that there is something fundamentally wrong with my approach as I only get “call to member function on null”. But can’t find a solution to it.

Any one that could point me in the right direction to solve this?

Where exactly do you get that error? Please post the stack trace.

Here you create a blocks collection (i.e. multiple blocks), but then you try to call image on that collection. That doesn’t make sense, so you would have to catch the first block.

$block    = $article->work()->toBlocks()->first();

Although I wonder why you are using blocks at all if there is only ever one block.

If you cast an image object to string, you get an img html element.

1 Like

I get the error from Kirby when trying to visiting the json template i’ve made. As I don’t need a standard template for this I’ve put all code in a template called masonry.php.

$block    = $article->work()->toBlocks()->first();

I this suggestion now but I get the same error.

I’ve also tried to get simpler things like:

    $src      = $block->type();

only the receive a similar error: Call to a member function type() on null.

There aren’t any elaborate reason behind the use of blocks, just like how visual they are especially when it comes to video.

Do all pages have this field filled? You definitely need an if statement here to make sure you have a block.

1 Like

Yes they do, just double check the be sure. But I agree an if statement will be necessary.

Okey seems like an if statement solved it :person_facepalming:
But can’t understand why since every page had an image block.

Thanks for your help! :slight_smile: