Skip to content

Commit

Permalink
Updating element api to return no elements if resource type or topics…
Browse files Browse the repository at this point in the history
… don't exist or blog categories does not exist
  • Loading branch information
LinneaImarc committed Apr 5, 2022
1 parent 9a7bfdb commit 8ce617b
Showing 1 changed file with 34 additions and 16 deletions.
50 changes: 34 additions & 16 deletions config/element-api.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,31 +85,49 @@
$resourceType = Craft::$app->request->getQueryParam('type');
$resourceTopic = Craft::$app->request->getQueryParam('topic');


if ($resourceType && $resourceTopic) {
$relatedTo[] = 'and';
}
$topicCategories = [];
$typeCategories = [];
$paramCount = 0;

if ($resourceType) {
$category = Category::findOne([
'group' => 'resourceTypes',
'slug' => $resourceType
]);
$resourceTypes = explode(',', $resourceType);
foreach ($resourceTypes as $type) {
$category = Category::findOne([
'group' => 'resourceTypes',
'slug' => $type
]);
if ($category) {
$typeCategories[] = $category;
}
}

$relatedTo[] = ["targetElement" => $category];
$paramCount++;
}

if ($resourceTopic) {
$category = Category::findOne([
'group' => 'resourceTopics',
'slug' => $resourceTopic
]);

$relatedTo[] = ["targetElement" => $category];
$resourceTopics = explode(',', $resourceTopic);
foreach ($resourceTopics as $topic) {
$category = Category::findOne([
'group' => 'resourceTopics',
'slug' => $topic
]);
if ($category) {
$topicCategories[] = $category;
}
}
$paramCount++;
}

$criteria['relatedTo'] = $relatedTo;
if ($paramCount > 1) {
$relatedTo[] = 'and';
}

if ($resourceType || $resourceTopic) {
$relatedTo[] = ["targetElement" => $typeCategories];
$relatedTo[] = ["targetElement" => $topicCategories];
$criteria['relatedTo'] = $relatedTo;
}

return [
'criteria' => $criteria,
'transformer' => function(Entry $entry) {
Expand Down

0 comments on commit 8ce617b

Please sign in to comment.