craftcms / element-api

Create a JSON API/Feed for your elements in Craft.
MIT License
498 stars 56 forks source link

Get slug of entries with same ID in other sites/locales #102

Closed boxadesign closed 5 years ago

boxadesign commented 5 years ago

I am using the element-api to get entries. What I would like to do is have the slug of entries in the other languages in the data that correspond with ID of each entry. This is so I can use this in my static site generator to create a language switcher. Ideally I'd like to get an array of slugs for all entries with the same ID. I'd like to get back something like this:

'slugs': [
   'en': 'some-en-slug',
   'cy': 'some-cy-slug',
   'fr': 'some-fr-slug'
 ]

My current simple endpoint is below:

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

return [
'endpoints' => [
    'posts.json' => function() {
        $langHandle = Craft::$app->request->getQueryParam('lang', 'en');
        return [
            'elementType' => Entry::class,
            'criteria' => ['section' => 'page', 'site' => $langHandle],
            'transformer' => function(Entry $entry) {
                $parent = $entry->getParent();
                return [
                    'id' => $entry->id,
                    'type' => $entry->type['handle'],
                    'title' => $entry->title,
                    'slug' => $entry->slug,
                    'locale' => $entry->locale,
                    'body' => $entry->body,
                    'level' => $entry->level,
                    'parent' => $parent ? [
                        'title' => $parent->title,
                        'url' => $parent->url,
                    ] : null,
                ];
            }
        ];
    }
]
];
elodiegrondin commented 4 years ago

Hi @boxadesign did you find something for your issue ?

brandonkelly commented 2 years ago

Here’s how you could do this as of Craft 3.5 or later:

use craft\elements\Entry;
use craft\helpers\ArrayHelper;

'transformer' => function(Entry $entry) {
    return [
        'title' => $entry->title,
        'slugs' => array_map(function(Entry $loc) {
            return $loc->slug;
        }, ArrayHelper::index($entry->getLocalized()->all(), 'site.handle')),
    ];
}