ModifierPoolTrait ================= * Published: 2019-12-22 * Author: Nickolas Burr .. contents:: Table of Contents :local: Description ----------- Several Magento UI components depend on data from data providers. Often times, we need to conditionally modify data provided by a data provider, so data modifiers were introduced to solve this problem. Traditionally, we would need to override a class in order to make those modifications, but Magento provides an improved approach with data modifiers, which accepts the respective metadata/data as an argument, and returns the modified version to the data provider. In the example below, we've created a trait called ``ModifierPoolTrait``, which can be used by a data provider class to access the respective data modifier pool. Usage ----- .. code-block:: php modifierPool = $modifierPool; } /** * @return array */ public function getMeta(): array { /** @var array $meta */ $meta = parent::getMeta(); /** @var ModifierInterface[] $modifiers */ $modifiers = $this->getModifiers(); /** @var ModifierInterface $modifier */ foreach ($modifiers as $modifier) { $meta = $modifier->modifyMeta($meta); } return $meta; } /** * @return array */ public function getData(): array { if (!empty($this->loadedData)) { return $this->loadedData; } /** @var EntityInterface[] $items */ $items = $this->getCollection()->getItems(); /** @var EntityInterface $entity */ foreach ($items as $entity) { $this->loadedData[$entity->getId()] = $entity->getData(); } /** @var ModifierInterface[] $modifiers */ $modifiers = $this->getModifiers(); /** @var ModifierInterface $modifier */ foreach ($modifiers as $modifier) { $this->loadedData = $modifier->modifyData($this->loadedData); } return $this->loadedData; } } .. code-block:: php Vendor\Package\Ui\DataModifier\Entity\DataModifier 10 Vendor\Package\Ui\DataModifier\Entity\Pool ``` Source ------ .. code-block:: php modifierPool; } /** * @return ModifierInterface[] */ public function getModifiers(): array { return $this->getModifierPool() ->getModifiersInstances(); } }