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
foreach($entry->getFieldValue('contentMatrix')->all() as $block)
? Please make sure all entry types have a field in the layoutcontentMatrix
– Robin Schambach Jun 11 '18 at 12:41