Each of my entries has multiple categories (e.g. series, disciplines, and stages). I can get a list of elements related to a single category but I'd also like to get the category information as well (title, summary etc). Ideally, I'd like to pass the $slug
to the transformer so I can grab the category from there, is that possible?
Here's my current code for an endpoint from elementapi.php
'api/series/<slug:{slug}>.json' => function($slug) {
// get category by slug
$series = craft()->elements->getCriteria(ElementType::Category);
$series->group = 'series';
$series->slug = $slug;
$series->first();
return [
'elementType' => ElementType::Entry,
'criteria' => [
'section' => ['lessons'],
'relatedTo' => ['targetElement' => $series]
],
'transformer' => function(EntryModel $entry) {
return structureEntry($entry);
}
];
},
/*-------------------------------------------*/
function structureEntry($entry) {
return [
'id' => (int)$entry->id,
'title' => $entry->title,
'slug' => $entry->slug,
'summary' => $entry->summary ? $entry->summary : null,
'featuredImage' => $entry->featuredImage->first() ? getImageSizes($entry->featuredImage->first()) : null,
'body' => $entry->body ? (string)$entry->body : null,
'series' => $entry->series ? getCategoryData($entry->series) : null,
'stage' => $entry->stage ? getCategoryData($entry->stage) : null,
'disciplines' => $entry->discipline ? getCategoryData($entry->discipline) : null
];
}
function getCategoryData($categories) {
$cats = array();
for($i = 0; $i < count($categories); $i++) {
$cats[$i] = [
'id' => (int)$categories[$i]->id,
'title' => $categories[$i]->title,
'slug' => $categories[$i]->slug,
'summary' => $categories[$i]->summary
];
}
return $cats;
}
Ideally, I'd like to do something like this:
'api/series/<slug:{slug}>.json' => function($slug) {
// get category by slug
$series = craft()->elements->getCriteria(ElementType::Category);
$series->group = 'series';
$series->slug = $slug;
$series->first();
return [
'elementType' => ElementType::Entry,
'criteria' => [
'section' => ['lessons'],
'relatedTo' => ['targetElement' => $series]
],
'transformer' => function(EntryModel $entry) {
$category = craft()->elements->getCriteria(ElementType::Category);
$category->group = 'series';
$category->slug = $slug;
$category->first();
return array_merge(structureEntry($entry), structureCategory($category));
}
];
},
Any help would be appreciated, thanks!