File displayers (Pro)
Define a new displayer
Define a new displayer class :
<?php use Ryssbowh\CraftThemes\models\FileDisplayer; class MyFileDisplayer extends FileDisplayer { /** * @var string */ public static $handle = 'my-displayer'; /** * @inheritDoc */ public function getName(): string { return \Craft::t('themes', 'My Displayer'); } /** * @inheritDoc */ public static function getKindTargets(): array { return ['javascript', 'html', 'php', 'text', 'xml', 'json']; } /** * @inheritDoc */ protected function getOptionsModel(): string { return MyFileDisplayer::class; } }
Displayers handles can only contain letters, numbers and hyphens.
Your file displayer class must extend the FileDisplayerInterface
(the FileDisplayer
model should be used to extend from) and define one or several asset kinds in the getKindTargets
method. The '*' can be used to indicate this displayer can handle all asset kinds.
Register your displayer by listening to the event :
Event::on( FileDisplayerService::class, FileDisplayerService::EVENT_REGISTER_DISPLAYERS, function (RegisterFileDisplayerEvent $event) { $event->register(MyFileDisplayer::class); });
Options
Your displayer must define an option class which must be a configurable options class.
You may not have options for your displayer in which case you'd just create an empty class, but other plugins may want to register options on your displayer.
<?php use Ryssbowh\CraftThemes\models\FieldDisplayerOptions; class MyFieldDisplayerOptions extends FieldDisplayerOptions { /** * @inheritDoc */ public function defineOptions(): array { return [ 'my-option' => [ 'field' => 'lightswitch', 'label' => \Craft::t('themes', 'My option') ] ]; } /** * @inheritDoc */ public function defineDefaultValues(): array { return [ 'my-option' => true ]; } /** * @inheritDoc */ public function defineRules(): array { return [ ['my-option', 'boolean', 'trueValue' => true, 'falseValue' => false] ]; } }
Default displayer
You can set your displayer to be the default for the fields they handle by overriding the method isDefault(string $kind): bool
. This will only apply for fields created from this point on.
Modify kind targets
You can change which asset kinds any displayer can handle :
Event::on( Code::class, FileDisplayerService::EVENT_KIND_TARGETS, function (RegisterDisplayerTargetsEvent $e) { $e->targets[] = 'audio'; });
Modify default displayer
Set the default displayer for any asset kind :
Event::on( FileDisplayerService::class, FileDisplayerService::EVENT_DEFAULT_DISPLAYERS, function (RegisterFileDefaultDisplayerEvent $e) { $e->defaults['audio'] = 'my-displayer-handle'; });