1

I have Single Section(entry) with Matrix field which contains Assets in blocks. I'm trying to fetch assets from a single Matrix block.

My element-api.php code is:

<?php

use craft\elements\Entry;
use craft\elements\MatrixBlock;
use craft\elements\Asset;
use craft\helpers\UrlHelper;

return [
  'endpoints' => [
    'api/portfolio/<blockId:\d+>.json' => function($blockId) {
      return [
        'elementType' => MatrixBlock::class,
        'criteria' => ['ownerId' => '4351', 'fieldId' => '218', 'id' => $blockId],
        'pretty' => true,
      ];
    },
  ]
];

Part of output is:

   "join": [
            [
                "INNER JOIN",
                "{{%relations}} relations",
                [
                    "and",
                    "[[relations.targetId]] = [[elements.id]]",
                    {
                        "relations.sourceId": "4402",
                        "relations.fieldId": "219"
                    },
                    [
                        "or",
                        {
                            "relations.sourceSiteId": null
                        },
                        {
                            "relations.sourceSiteId": "1"
                        }
                    ]
                ]
            ]
        ],

so it looks like I'm trying to access related field id 219 which is Assets field inside Matrix block.

Fields structure: enter image description here

Any ideas?

2

You need a transformer

'transformer' => function(MatrixBlock $element){
    return [
       'image' => $element->getFieldValue('assetFieldHandle')->one()->getUrl() 
    ];
} 
|improve this answer|||||

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.