1

I recently started using the Elements API and I made up a recipe site as an example project. It's pretty easy to output the recipes as json data.

But I now want some more control about the output of the data and only query a specific subset of the recipes. As long as I have the data needed for the selection directly in the recipes entries it's easy to filter or sort them accordingly. However sometimes I might want to manually pick and order entries. One solution would be to create extra attributes in the recipe entries, but this seems messy.

I would like to do that with an entry selection field since this seems to be the most intuitive option for content authors. My question is how can I use the data of an entry field to limit the output? My current solutions seem really bad:

  1. I simply query each entry separately by id, but this seems like a terrible idea in particular for a larger selection.

  2. I load all data and do the cleanup in Javascript. Even though the images at least wouldn't get loaded this way it seems like an increasingly bad idea with an increasing number of total entries.

  3. The best solution for now seems to create an endpoint for the entry that contains the entry selection field and use the transformer to output the all the needed data - I miss the nice pagination / meta data that way however.

'transformer' => function(Entry $entry) {
     $selection =  [];
     foreach ($entry->selectedRecipes as $block) {
          $selection[] = [ array(
                          'title' => $block->title,
                          'id' => $block->id,
                          ...
                           )
                         ];
             }
     return [ 'recipes' => $selection,

This seems like a really basic problem and any hints on how to solve this problem are greatly appreciated.

Thank you

1

You could use the relatedTo parameter (docs) to query recipes related to the entry that has your Entries field on. Something like:

return [
    'elementType' => Entry::class,
    'criteria' => [
        'section' => 'recipes',
        'relatedTo' => ['sourceElement' => $entryWithEntriesField]
],

Where $entryWithEntriesField is the entry (or id of the entry) that contains the entry selection field would return the list of recipes attached to that entry.

| improve this answer | |
  • Thank you - that works perfect. – io_berlin Dec 9 '19 at 19:00

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.