Working on an element-api.php file from a Craft CMS project. Has a lot of helper functions. I added a category called disciplines. I'm trying to expose the values for each entry.
Here's the whole helper function I'm working on:
// Get all projects, by date, newest first
function getAllProjects() {
$caseStudies = [];
$query = \craft\elements\Entry::find();
$query->section('caseStudies');
$query->orderBy('postDate desc');
foreach ($query->all() as $page) {
$isPublic = $page->public;
$parent = $page->getSection()->handle;
if ($isPublic) {
$serviceData = [];
foreach ($page->modules->all() as $module) {
switch ($module->type->handle) {
case 'service':
$service = $module->service->one();
if ($service) {
$serviceData[] = [
'id' => $service->service->one()->id,
'title' => $service->service->one()->title,
];
}
break;
}
}
$coverColor = [
'r' => $page->coverColor ? $page->coverColor->r : 0,
'g' => $page->coverColor ? $page->coverColor->g : 0,
'b' =>$page->coverColor ? $page->coverColor->b : 0,
];
$caseStudies[] = [
'id' => $page->id,
'title' => $page->title,
'meta' => [
'navigationColor' => $page->navigationColor->value,
'title' => $page->metaTitle ? $page->metaTitle : $page->title,
'description' => $page->metaDescription,
],
'slug' => $page->slug,
'postDate' => date("d-m-Y",$page->postDate->getTimestamp()),
'json' => UrlHelper::url("work/{$page->slug}.json"),
'parent' => $parent,
'headline' => $page->headline,
'client' => $parent === 'caseStudies' ? $page->client->one()->title : null,
'services' => $serviceData,
'discipline' => array_map(function (CategoryModel $category) {
return [
'id' => $category->id,
'title' => $category->title,
];
}, $page->discipline->find()),
'cover' => handelImages($page->cover->all()),
'coverColor' => $coverColor,
'coverVideo' => [
'source' => $page->coverVideo
]
];
}
}
return $caseStudies;
}
Everything works except in the caseStudies array I have added this line:
'discipline' => array_map(function (CategoryModel $category) {
return [
'id' => $category->id,
'title' => $category->title,
];
}, $page->discipline->find()),
which returns the error: Argument 1 passed to {closure}() must be an instance of CategoryModel, instance of craft\elements\Category given
site is at Craft 3.3.15. Element-Api plugin is 2.6.0
This worked. Found a tag example right on the github page https://github.com/craftcms/element-api