Skip to content

Instantly share code, notes, and snippets.

@brandonkelly
Last active April 11, 2020 23:16
Show Gist options
  • Save brandonkelly/347d357dc29db938209f425d42b6ccc8 to your computer and use it in GitHub Desktop.
Save brandonkelly/347d357dc29db938209f425d42b6ccc8 to your computer and use it in GitHub Desktop.
Custom Preview Target for Craft 3.2
<?php
// -- modules/Module.php --
namespace modules;
use Craft;
use craft\base\Element;
use craft\elements\Entry;
use craft\events\RegisterPreviewTargetsEvent;
use craft\events\RegisterUrlRulesEvent;
use craft\helpers\UrlHelper;
use craft\web\UrlManager;
use yii\base\Event;
class Module extends \yii\base\Module
{
/**
* Initializes the module.
*/
public function init()
{
// Set a @modules alias pointed to the modules/ directory
Craft::setAlias('@modules', __DIR__);
// Set the controllerNamespace based on whether this is a console or web request
if (Craft::$app->getRequest()->getIsConsoleRequest()) {
$this->controllerNamespace = 'modules\\console\\controllers';
} else {
$this->controllerNamespace = 'modules\\controllers';
}
parent::init();
Event::on(UrlManager::class, UrlManager::EVENT_REGISTER_SITE_URL_RULES, function(RegisterUrlRulesEvent $e) {
$e->rules['test-target'] = 'module/test/test';
});
Event::on(Entry::class, Entry::EVENT_REGISTER_PREVIEW_TARGETS, function(RegisterPreviewTargetsEvent $e) {
/** @var Element $element */
$element = $e->sender;
$e->previewTargets[] = [
'label' => 'Test',
'url' => UrlHelper::siteUrl('test-target', [
'elementId' => $element->id,
'siteId' => $element->siteId,
]),
];
// Do this if you want to protect the preview target from public access:
Craft::$app->getSession()->authorize('customAuthorziationKey:' . $element->id);
});
}
}
<?php
// -- modules/controllers/TestController.php --
namespace modules\controllers;
use craft\base\Element;
use craft\web\Controller;
class TestController extends Controller
{
public function actionTest(int $elementId, int $siteId)
{
// Do this if you want to protect the preview target from public access:
$this->requireAuthorization('customAuthorizationKey:' . $elementId);
/** @var Element $element */
$element = \Craft::$app->getElements()->getElementById($elementId, null, $siteId);
return $this->asRaw($element->title);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment