diff --git a/CHANGELOG-WIP.md b/CHANGELOG-WIP.md index 499617177ba..9af8ba64a72 100644 --- a/CHANGELOG-WIP.md +++ b/CHANGELOG-WIP.md @@ -5,6 +5,8 @@ - Added a `one()` alias for `first()` to collections. ([#11134](https://github.com/craftcms/cms/discussions/11134)) - Added `craft\console\controllers\UsersController::$activate`. - Added `craft\elements\conditions\ElementCondition::$sourceKey`. +- Added `craft\elements\db\ElementQuery::EVENT_AFTER_POPULATE_ELEMENTS`. ([#11262](https://github.com/craftcms/cms/discussions/11262)) +- Added `craft\events\PopulateElementsEvent`. ### Changed - Improved pagination UI accessibility. ([#11126](https://github.com/craftcms/cms/pull/11126)) diff --git a/src/elements/db/ElementQuery.php b/src/elements/db/ElementQuery.php index 9b6c34dc1e1..2e3ac238e2a 100644 --- a/src/elements/db/ElementQuery.php +++ b/src/elements/db/ElementQuery.php @@ -23,6 +23,7 @@ use craft\errors\SiteNotFoundException; use craft\events\CancelableEvent; use craft\events\PopulateElementEvent; +use craft\events\PopulateElementsEvent; use craft\helpers\ArrayHelper; use craft\helpers\Db; use craft\helpers\ElementHelper; @@ -69,6 +70,13 @@ class ElementQuery extends Query implements ElementQueryInterface */ public const EVENT_AFTER_POPULATE_ELEMENT = 'afterPopulateElement'; + /** + * @event PopulateElementEvent The event that is triggered after an element is populated. + * + * If [[PopulateElementEvent::$element]] is replaced by an event handler, the replacement will be returned by [[createElement()]] instead. + */ + public const EVENT_AFTER_POPULATE_ELEMENTS = 'afterPopulateElements'; + /** * @var string The name of the [[ElementInterface]] class. * @phpstan-var class-string @@ -2881,6 +2889,16 @@ private function _createElements(array $rows): array if ($this->with) { Craft::$app->getElements()->eagerLoadElements($this->elementType, $elements, $this->with); } + + // Fire an 'afterPopulateElements' event + if ($this->hasEventHandlers(self::EVENT_AFTER_POPULATE_ELEMENTS)) { + $event = new PopulateElementsEvent([ + 'elements' => $elements, + 'rows' => $rows, + ]); + $this->trigger(self::EVENT_AFTER_POPULATE_ELEMENTS, $event); + $elements = $event->elements; + } } return $elements; diff --git a/src/events/PopulateElementsEvent.php b/src/events/PopulateElementsEvent.php new file mode 100644 index 00000000000..cdba94d5097 --- /dev/null +++ b/src/events/PopulateElementsEvent.php @@ -0,0 +1,30 @@ + + * @since 4.1.0 + */ +class PopulateElementsEvent extends Event +{ + /** + * @var ElementInterface[] The populated elements + */ + public array $elements; + + /** + * @var array[] The element query’s raw result data + */ + public array $rows; +}