2

So I'm trying to get my Matrix as JSON with the Craft CMS Element API plugin.

<?php

use Craft\elements\Entry;

return [
    'endpoints' => [
        'api/sites' => [
            'elementType' => craft\elements\Entry::class,
            'criteria' => ['section' => 'sites'],
            'elementsPerPage' => 1,
            'transformer' => function(Entry $entry) {
                $matrixBlocks =[];
                foreach ($entry->contentMatrix as $block) {
                    switch ($block->type->handle) {
                        case 'sectionTitleBlock':
                            $matrixBlocks[] = [
                                'content' => $block->sectionTitleBlock
                            ];
                            break;
                    }
                }
                return [
                    'matrix' => $matrixBlocks,
                ];
            },
            'paginate' => false,
            'pretty' => true,
        ],
    ]
];

The error message im getting is

"error": { "code": 2, "message": "Invalid argument supplied for foreach()" }

I think the problem is that $entry->contentMatrix is giving me a MatrixBlockQuery Element.

$sectionTitleBlock is a normal text field

3
  • 2
    Could you please try the correct syntax foreach($entry->getFieldValue('contentMatrix')->all() as $block)? Please make sure all entry types have a field in the layout contentMatrix Commented Jun 11, 2018 at 12:41
  • Yes. That fixed my problem! Thank you. May i ask were you got this correct syntax from? I can't find it on the plugins github page.
    – Leonardo
    Commented Jun 12, 2018 at 11:30
  • It has nothing to do with the plugin, it's just the correct syntax but most people dislike it or don't use that. You should take a look at the source code, you'll see it everywhere Commented Jun 12, 2018 at 11:40

1 Answer 1

2

In order to get all related items from a BaseRelationField you'll need this syntax

$entry->getFieldValue('contentMatrix')->all() 

Thus your loop will be

foreach($entry->getFieldValue('contentMatrix')->all() as $block){

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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