0

I have few entry ids from a plugin(donkeytail), and are arranged in an array,

I need to loop through that array and get title, slug, etc of each entry.

$entry->pins = ["106","122","114","134"...]

Endpoint:

'single.json' => function() {
        return [
            'criteria' => ['section' => 'home'], 
            'elementType' => Entry::class,        
            'transformer' => function(Entry $entry) {
                  $entryData = (object)[];
                  $entryData->pins = $entry->pins;
                  $entryData->pinnedEntries = (object)[];
                  foreach ($entry->pins as $item) {
                       *Needed Suggestion here to get entry by id ($item)*
                  }
                  return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                    'entryData' => $entryData,
                  ];

        }
}

1 Answer 1

0

You can use an entry query to retrieve the entries by their IDs and then use array_map to convert that to an associative array of the properties you want to return for those entries.

use craft\elements\Entry;

'transformer' => function (Entry $entry) {
    $entryData = (object) [];
    $entryData->pins = $entry->pins;

    $pinnedEntries = Entry::find()->id($entryData->pins)->status(null)->all();
    $entryData->pinnedEntries = array_map(fn (Entry $entry) => [
        'id' => $entry->id,
        'slug' => $entry->slug,
        'title' => $entry->title,
        'myCustomField' => $entry->getFieldValue('myCustomField'),
    ], $pinnedEntries);
    return [
        'title' => $entry->title,
        'url' => $entry->url,
        'entryData' => $entryData,
    ];
}

You can also use an advanced query with a custom select statement and use asArray to get the associative array directly from the query. That's a bit more involved, but will improve performance in case you run into any bottlenecks.

Your Answer

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

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