From 924f535293bb0e9f743bc6ad31dc53f42f19a8f5 Mon Sep 17 00:00:00 2001 From: matze Date: Tue, 10 Dec 2024 23:30:43 +0100 Subject: [PATCH] added unit to ingredient with constraint --- src/Plugin/Asset/AssetType/Ingredient.php | 12 +++++++++++- .../Constraint/SubstanceIngredientsConstraint.php | 1 + .../SubstanceIngredientsConstraintValidator.php | 10 ++++++++++ 3 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/Plugin/Asset/AssetType/Ingredient.php b/src/Plugin/Asset/AssetType/Ingredient.php index ca60008..28a679f 100644 --- a/src/Plugin/Asset/AssetType/Ingredient.php +++ b/src/Plugin/Asset/AssetType/Ingredient.php @@ -32,7 +32,17 @@ class Ingredient extends FarmAssetType { 'amount_field' => [ 'type' => 'fraction', 'label' => $this->t('Amount'), - 'description' => $this->t('How much of the chemical is in the ingredient in g/l'), + 'description' => $this->t('How much of the chemical is in the ingredient'), + 'required' => TRUE, + ], + 'unit_field' => [ + 'type' => 'entity_reference', + 'label' => $this->t('Unit'), + 'description' => $this->t('What unit is the ingredient measured in?'), + 'target_type' => 'taxonomy_term', + 'target_bundle' => 'unit', + 'auto_create' => TRUE, + 'multiple' => FALSE, 'required' => TRUE, ], ]; diff --git a/src/Plugin/Validation/Constraint/SubstanceIngredientsConstraint.php b/src/Plugin/Validation/Constraint/SubstanceIngredientsConstraint.php index 873c2e1..6a4fd56 100644 --- a/src/Plugin/Validation/Constraint/SubstanceIngredientsConstraint.php +++ b/src/Plugin/Validation/Constraint/SubstanceIngredientsConstraint.php @@ -23,5 +23,6 @@ use Symfony\Component\Validator\Constraint; final class SubstanceIngredientsConstraint extends Constraint { public string $notUnique = 'Some chemicals were entered twice.'; + public string $notTheSameUnit = 'All ingredients need to be measured with the same unit.'; } diff --git a/src/Plugin/Validation/Constraint/SubstanceIngredientsConstraintValidator.php b/src/Plugin/Validation/Constraint/SubstanceIngredientsConstraintValidator.php index 3426aaf..b9a0fb7 100644 --- a/src/Plugin/Validation/Constraint/SubstanceIngredientsConstraintValidator.php +++ b/src/Plugin/Validation/Constraint/SubstanceIngredientsConstraintValidator.php @@ -23,15 +23,25 @@ final class SubstanceIngredientsConstraintValidator extends ConstraintValidator ); } $seen_quantities = []; + $old_unit = null; foreach ($items as $delta => $item) { $ingredient = \Drupal::entityTypeManager()->getStorage('asset')->load($item->target_id); $chemical_id = $ingredient->chemical_field->target_id; + $new_unit = $ingredient->unit_field->target_id; if (isset($seen_quantities[$chemical_id])) { $this->context->buildViolation($constraint->notUnique) ->atPath($delta) ->addViolation(); } + if (isset($old_unit)) { + if ($old_unit != $new_unit) { + $this->context->buildViolation($constraint->notTheSameUnit) + ->atPath($delta) + ->addViolation(); + } + } $seen_quantities[$chemical_id] = true; + $old_unit = $new_unit; } } }