2

Is there a way to force a request type (HttpRequestService::isCpRequest vs. HttpRequestService::isSiteRequest)?

In my case I'm generating some indexing data on entries.onSaveEntry. I'm trying to use some UrlHelper methods, but the resulting urls are wrong, since it thinks it is a cp request.

I have to do something like this load templates:

craft()->templates->setTemplateMode(TemplateMode::Site);

Is there any way to do something similar for request type?

1 Answer 1

2

There's no setRequestType() method or the like, no. The HttpRequestService will consider any request with the cpTrigger in its URL a control panel request, and I don't see any easy way around that.

It's a bit convoluted, but what you could do is to wrap whatever code you're currently executing in your entries.onSaveEntry in a controller action method, and then use Guzzle in your onSaveEntry event handler to trigger a site request (i.e. a request without the cpTrigger in the URL) to that action.

Here's how your controller action could look:

<?
namespace Craft;

class MyPluginController extends BaseController
{

    protected $allowAnonymous = ['actionGenerateIndex'];

    public function actionGenerateIndex ()
    {

        // Get entry (based on a ?entryId URL parameter
        $entryId = craft()->request->getParam('entryId');
        $entry = craft()->elements->getCriteria(ElementType::Entry, [
            'id' => $entryId,
        ])->first();

        // ...your code to generate the index data here

    }
}

Here's how you could fire off a request to this action using Guzzle, stripping the cpTrigger from the action URL to make sure Craft treats the action as a site request:

craft()->on('entries.onSaveEntry', function (Event $e) {

    // Get entry
    $entry = $e->params['entry'];

    // Get action URL, strip the `cpTrigger` segment
    $actionUrl = UrlHelper::getActionUrl('myPlugin/generateIndex', [
        'entryId' => $entry->id,
    ]);
    $actionUrl = str_replace(craft()->config->get('cpTrigger').'/', '', $actionUrl);

    // Request action
    $client = new Guzzle\Http\Client();
    $request = $client->get($actionUrl, [], [
      'headers' => [
        'X-Requested-With' => 'XMLHttpRequest',
      ],
    ]);
    $request->send();

});
1
  • 1
    Thanks @matsmikkel! Yep, a bit icky, but if I really needed to, your solution is a good one. I suppose I should make a FR for forcing the request type.
    – Tim Kelty
    Commented Dec 4, 2016 at 19:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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