2

I need to get the currentSite in Element API. How can this be achieved? Is it as a slug in the endpoint URL? or as a Query param? Here is the current code:

<?php

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

return [
    'defaults' => [
        'resourceKey' => 'suggestions',
        'cache' => false,
        'paginate' => false,
        'pretty' => true,
    ],
    'endpoints' => [
        'api/search.json' => function() {

        $searchQuery = Craft::$app->request->getQueryParam('query');
        $site = Craft::$app->request->getQueryParam('site');

        $sectionHandles = [
            'pages',
            'news',
        ];

        // Search criterias
        $criteria = [
            'section' => $sectionHandles,
            'search' => $searchQuery,
            'site' => $site,
            'orderBy' => 'score',
            'limit' => 10,
        ];

            return [
                'elementType' => Entry::class,
                'criteria' => $criteria,
                'paginate' => false,

            'transformer' => function(craft\elements\Entry $entry) {

                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                ];
            },

            ];
        },
    ]
];
2

The currentSite property from the Sites service is what you're looking for. Here's how you would use it:

'api/search.json' => function() {

    $siteHandle = Craft::$app->getSites()->currentSite->handle;

    ...

    $criteria = [
        'site' => $siteHandle,
        ...
    ];

    return [
        ...
    ];
},
2
  • Thanks for the speedy reply. So, in essence this should work. One question remains: the JS for the autocomplete somehow needs to know what the current site is. How would one pass siteHandle to Javascript? Right now I'm doing it using the window object, but it feels a bit hackish.
    – nfq
    Jul 17 '20 at 13:29
  • @nfq honestly not sure why you'd need the siteHandle for the autocomplete functionality, but I typically pass that and any other global info I need via the window object like you're describing... Jul 17 '20 at 17:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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