Skip to content

Deferred event handling for bulk ops#16655

Merged
brandonkelly merged 3 commits into5.7from
feature/cms-1362-track-element-events-with-bulkopevent
Feb 7, 2025
Merged

Deferred event handling for bulk ops#16655
brandonkelly merged 3 commits into5.7from
feature/cms-1362-track-element-events-with-bulkopevent

Conversation

@brandonkelly
Copy link
Copy Markdown
Member

@brandonkelly brandonkelly commented Feb 7, 2025

Introduces a new craft\events\BulkOpEvent::defer() method, which can be used in place of Event::on() when you want to track whether an event occurs during a bulk operation, and handle it after the bulk operation is complete.

use craft\elements\Entry;
use craft\events\BulkOpEvent;
use craft\helpers\Db;

BulkOpEvent::defer(
    Entry::class,
    Entry::EVENT_AFTER_SAVE,
    function (BulkOpEvent $event) {
        // Fetch all the entries that were affected
        $entries = Entry::find()->inBulkOp($event->key)->status(null);
        foreach (Db::each($entries) as $entry) {
            // ...
        }
    },
);

The event handler is passed the same BulkOpEvent object you’d get if you were listening to craft\services\Elements::EVENT_AFTER_BULK_OP. (The event may have occurred on a previous request, so there’s no way to keep track of the specific event objects that were fired.)

@linear
Copy link
Copy Markdown

linear Bot commented Feb 7, 2025

@brandonkelly brandonkelly merged commit d1b732e into 5.7 Feb 7, 2025
@brandonkelly brandonkelly deleted the feature/cms-1362-track-element-events-with-bulkopevent branch February 7, 2025 22:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant