Перейти к основному содержимому

Слушатели событий и мероприятий

Общий

Pimcore предоставляет большое количество событий, которые упускаются во время выполнения функций Pimcore. Эти события могут быть Используется для зацепления во многие функции Pimcore, такие как сохранение объекта, актива или документа, и могут использоваться для изменения или расширения Поведение Pimcore по умолчанию.

Наиболее распространенным вариантом использования для событий является использование их в пакет/расширение, но Конечно, вы можете использовать их также в любом месте вашего кода или в конфигурации инъекции зависимости (config/services.yaml).

Pimcore реализует стандартный диспетчер Symfony Framework Event и просто добавляет некоторые специфические события Pimcore, Таким образом, вы также можете подписаться на все основные события Symfony и события, вызванные произвольными связями Symfony.

По этой причине рекомендуется взглянуть на Symfony {p1} Во -первых, что охватывает все основы в этом вопросе.

Доступные события

Все события Pimcore определены и задокументированы как постоянная на компонентных классах:

Примеры

зацепите предварительное событие активов, документов и объектов

В следующем примере показано, как зарегистрировать события для активов, документов и объектов

в вашем {c31}:

services:  
App\EventListener\TestListener:
tags:
- { name: kernel.event_listener, event: pimcore.asset.preUpdate, method: onPreUpdate }
- { name: kernel.event_listener, event: pimcore.document.preUpdate, method: onPreUpdate }
- { name: kernel.event_listener, event: pimcore.dataobject.preUpdate, method: onPreUpdate }

in your listener class src/EventListener/TestListener

<?php  

namespace App\EventListener;

use Pimcore\Event\Model\ElementEventInterface;
use Pimcore\Event\Model\DataObjectEvent;
use Pimcore\Event\Model\AssetEvent;
use Pimcore\Event\Model\DocumentEvent;

class TestListener
{
public function onPreUpdate(ElementEventInterface $e): void
{
if ($e instanceof AssetEvent) {
// do something with the asset
$foo = $e->getAsset();
} else if ($e instanceof DocumentEvent) {
// do something with the document
$foo = $e->getDocument();
} else if ($e instanceof DataObjectEvent) {
// do something with the object
$foo = $e->getObject();
$foo->setMyValue(microtime(true));
// we don't have to call save here as we are in the pre-update event anyway ;-)
}
}
}

Hook into the list of objects in the tree, the grid list and the search panel

There are some global events having effect on several places. One of those is pimcore.admin.object.list.beforeListLoad. The object list can be modified (changing condition for instance) before being loaded. This global event will apply to the tree, the grid list, the search panel and everywhere objects are listed in the Pimcore GUI. This way, it is possible to create custom permission rules to decide if the object should or not be listed (for instance, the user must be the owner of the object, ...).

It extends the possibility further than just limiting list permissions folder by folder depending the user/role object workspace. To ensure maximum security, it is advisable to combine this with an object DI to overload isAllowed method with the same custom permission rules. This way proper permission is ensuring all the way (rest services, ...).

Hook into the Open Document|Asset|Data Object dialog

By the default, Pimcore tries to a resolve an element by its ID or path. You can change this behavior by handling the {P30} event and implement your own logic.

    \Pimcore::getEventDispatcher()->addListener(AdminEvents::RESOLVE_ELEMENT, function(ResolveElementEvent $event) {  
$id = $event->getId();
if ($event->getType() == "object") {
if (is_numeric($event->getId())) {
return;
}

$listing = new News\Listing();
$listing->setLocale('en');
$listing->setLimit(1);
$listing->setCondition('title LIKE ' . $listing->quote('%' . $id . '%'));
$listing = $listing->load();
if ($listing) {
$id = ($listing[0])->getId();
$event->setId($id);
}
}

Asset Upload Path

Certain data types (like image, relations, etc ...) allow you to specify a dedicated upload path which defaults to '/_default_upload_bucket' if not otherwise specified in the config yml file or in the class definition.

The {P31} event allows you to dynamically modify the target path depending on the object it will be assigned to. Additional contextual information (like fieldname, fieldcollection index number, etc... ) could be utilized to support the decision.

The contextual info provided is the same as described {P32}:

Example Code: For the demo instance, this sample code would place an image which is dragged onto the image_1 field of object 6 (in-enim-justo_2) into the /news/in-enim-justo_2/image_1 asset folder.

        \Pimcore::getEventDispatcher()->addListener(AssetEvents::RESOLVE_UPLOAD_TARGET,  
function(\Pimcore\Event\Model\Asset\ResolveUploadTargetEvent $event) {
$context = $event->getContext();
if ($context["containerType"] == "object") {
$objectId = $context["objectId"];
$newsObject = News::getById($objectId);
if ($newsObject) {
$fieldname = $context["fieldname"];
$targetPath = $newsObject->getPath() . $newsObject->getKey() . "/" . $fieldname;
$parent = \Pimcore\Model\Asset\Service::createFolderByPath($targetPath);
if ($parent) {
$event->setParentId($parent->getId());
}
}

}
});


Вы можете предложить улучшение документации или задать вопрос в комментариях.
Если вам нужна полноценная консультация — вы можете заказать её на нашем сайте.