Skip to content

Instantly share code, notes, and snippets.

@timkelty
Last active July 23, 2020 17:41
Show Gist options
  • Select an option

  • Save timkelty/b88fe56fb73325f0dfeae21cce63fcb4 to your computer and use it in GitHub Desktop.

Select an option

Save timkelty/b88fe56fb73325f0dfeae21cce63fcb4 to your computer and use it in GitHub Desktop.
Attaching behaviors by section
<?php
namespace modules\appmodule;
use Craft;
use craft\elements\Entry;
use craft\events\DefineBehaviorsEvent;
use yii\base\Event;
class Module extends \yii\base\Module
{
const SECTION_BEHAVIORS = [
'orders' => [
\modules\appmodule\behaviors\Order::class,
],
];
public function init()
{
Event::on(
Entry::class,
Entry::EVENT_DEFINE_BEHAVIORS,
function (DefineBehaviorsEvent $event) {
$entry = $event->sender;
// Explicitly checking for sectionId in the body,
// as it won't be set in $entry yet within the EVENT_BEFORE_SAVE event
$sectionId = $entry->sectionId || $this->request->getBodyParam('sectionId');
$section = $sectionId ? Craft::$app->sections->getSectionById($sectionId) : null;
// Bail early if no section yet
if (!$section) {
return;
}
$behaviors = self::SECTION_BEHAVIORS[$section->handle] ?? [];
$event->behaviors = array_merge($behaviors, $event->behaviors);
}
);
}
}
<?php
namespace modules\appmodule\behaviors;
use craft\elements\Entry;
use craft\events\ModelEvent;
use yii\base\Behavior;
class Order extends Behavior
{
public function events()
{
return [
Entry::EVENT_BEFORE_SAVE => function (ModelEvent $event) {
// This only works if we check for the sectionId body param
$event->sender->title = 'Entry::EVENT_BEFORE_SAVE from Behavior::events';
},
Entry::EVENT_AFTER_SAVE => function (ModelEvent $event) {
$entry = $event->sender;
// This always works
},
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment