From d4b24222eaf796ba34ce3e0db4cfab294da2f604 Mon Sep 17 00:00:00 2001 From: paul121 Date: Fri, 6 Aug 2021 09:27:45 -0700 Subject: [PATCH] Auto-populate material type term reference from a material inventory asset. --- .../farm_quantity_material.services.yml | 5 ++ .../QuantityEventSubscriber.php | 62 +++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 modules/quantity/material/farm_quantity_material.services.yml create mode 100644 modules/quantity/material/src/EventSubscriber/QuantityEventSubscriber.php diff --git a/modules/quantity/material/farm_quantity_material.services.yml b/modules/quantity/material/farm_quantity_material.services.yml new file mode 100644 index 00000000..98db705d --- /dev/null +++ b/modules/quantity/material/farm_quantity_material.services.yml @@ -0,0 +1,5 @@ +services: + farm_quantity_material.quantity_subscriber: + class: Drupal\farm_quantity_material\EventSubscriber\QuantityEventSubscriber + tags: + - { name: 'event_subscriber' } diff --git a/modules/quantity/material/src/EventSubscriber/QuantityEventSubscriber.php b/modules/quantity/material/src/EventSubscriber/QuantityEventSubscriber.php new file mode 100644 index 00000000..ae7deac5 --- /dev/null +++ b/modules/quantity/material/src/EventSubscriber/QuantityEventSubscriber.php @@ -0,0 +1,62 @@ + 'quantityPresave', + ]; + } + + /** + * Copy material_type from a material inventory asset to material quantity. + * + * @param \Drupal\quantity\Event\QuantityEvent $event + * Quantity event. + */ + public function quantityPresave(QuantityEvent $event) { + + $quantity = $event->quantity; + + // Bail if not a material quantity. + if ($quantity->bundle() !== 'material') { + return; + } + + // Bail if there is no inventory field or if it is empty. + if (!$quantity->hasField('inventory_asset') || $quantity->get('inventory_asset')->isEmpty()) { + return; + } + + // Get the referenced inventory asset. + /** @var \Drupal\asset\Entity\AssetInterface[] $assets */ + $assets = $event->quantity->get('inventory_asset')->referencedEntities(); + $asset = reset($assets); + + // Bail if not a material asset. + if (empty($asset) || $asset->bundle() !== 'material') { + return; + } + + // Copy the material asset material_type field to the material quantity. + if (!$asset->get('material_type')->isEmpty()) { + $material_type = $asset->get('material_type')->getValue(); + $quantity->set('material_type', $material_type); + } + } + +}