Field displayers (Pro)
Define a new displayer
Define a displayer class :
<?php use Ryssbowh\CraftThemes\models\FieldDisplayer; use Ryssbowh\CraftThemes\models\fields\Title; class MyFieldDisplayer extends FieldDisplayer { /** * @inheritDoc */ public static $handle = 'my-displayer'; /** * @inheritDoc */ public function getName(): string { return \Craft::t('themes', 'My Field'); } /** * @inheritDoc */ public static function getFieldTargets(): array { return [Title::class]; } /** * @inheritDoc */ protected function getOptionsModel(): string { return MyFieldDisplayerOptions::class; } }
Displayers handles can only contain letters, numbers and hyphens.
Your field displayer class must implements FieldDisplayerInterface
(the FieldDisplayer
model should be used to extend from) and define the field it can handle in its getFieldTargets
method.
Register your displayer by listening to the event :
Event::on( FieldDisplayerService::class, FieldDisplayerService::EVENT_REGISTER_DISPLAYERS, function (RegisterFieldDisplayerEvent $event) { $event->register(MyFieldDisplayer::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 $fieldClass): bool
. This will only apply for fields created from this point on.
Modify field targets
You can change which fields any displayer can handle :
Event::on( TitleTitle::class, FieldDisplayerService::EVENT_FIELD_TARGETS, function (RegisterDisplayerTargetsEvent $e) { $e->targets[] = MyField::class; });
Modify default displayer
Set the default displayer for any field:
Event::on( Title::class, FieldDisplayerService::EVENT_DEFAULT_DISPLAYER, function (RegisterFieldDefaultDisplayerEvent $event) { $event->default = 'my-displayer'; });
Note that this won't have any effect on fields already installed.
Date/Time displayers
This plugin works with the intl extension for all displayers handling date/time. All formats are expected to be in icu.
When outputing a date value in templates, you can use the format_datetime
filter :
{{ date|format_datetime(pattern=format,locale=craft.app.locale) }}