added unit to ingredient with constraint

This commit is contained in:
matze committed 2024-12-10 23:30:43 +01:00
1 parent 9227f828d6
commit 924f535293
3 files changed
+22 -1

No files matched your search

@@ -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.';
}
@@ -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;
}
}
}