1

I get this JSON error when trying to output content of a matrix block called proLinks using the Element API.

Call to a member function all() on null

The code is as follows (I've shortened it and removed the other content, this is the only one that I can't get to work):

<?php

use craft\elements\Entry;

return [
  'endpoints' => [
    'discproj.json' => function() {
      return [
        'elementType' => Entry::class,
        'criteria' => ['section' => 'dPs'],
        'transformer' => function(Entry $entry) {

          $linkBlocks = [];
          foreach ($entry->proLinks->all() as $block) {
            switch ($block->type->handle) {
              case 'external':
              $linkBlocks[] = [
                'externalTitle' => $block->externalTitle,
                'externalLink' => $block->externalLink,
              ];
              break;
            }
          }

          return [
            'projectLinks' => $linkBlocks,
          ];
        },
      ];
    },
  ]
];

I've looked at the other questions about this here, and they all seem to do things a little bit different from each other. I think I have the general structure, but there is obviously something missing.

1

I figured it out. Not every entry uses the matrix block, the error appears when the script hits that empty/non-existing block (null) it can't go looking for something inside it. Adding a conditional around the foreach solves it.

<?php

use craft\elements\Entry;

return [
  'endpoints' => [
    'discproj.json' => function() {
      return [
        'elementType' => Entry::class,
        'criteria' => ['section' => 'dPs'],
        'transformer' => function(Entry $entry) {

          $linkBlocks = null;
          if ($entry->proLinks) {
            foreach ($entry->proLinks->all() as $block) {
              switch ($block->type->handle) {
                case 'external':
                $linkBlocks[] = [
                  'externalTitle' => $block->externalTitle,
                  'externalLink' => $block->externalLink,
                ];
                break;
              }
            }
          }

          return [
            'projectLinks' => $linkBlocks,
          ];
        },
      ];
    },
  ]
];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.