added unit to ingredient with constraint
This commit is contained in:
@@ -32,7 +32,17 @@ class Ingredient extends FarmAssetType {
|
|||||||
'amount_field' => [
|
'amount_field' => [
|
||||||
'type' => 'fraction',
|
'type' => 'fraction',
|
||||||
'label' => $this->t('Amount'),
|
'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,
|
'required' => TRUE,
|
||||||
],
|
],
|
||||||
];
|
];
|
||||||
|
|||||||
@@ -23,5 +23,6 @@ use Symfony\Component\Validator\Constraint;
|
|||||||
final class SubstanceIngredientsConstraint extends Constraint {
|
final class SubstanceIngredientsConstraint extends Constraint {
|
||||||
|
|
||||||
public string $notUnique = 'Some chemicals were entered twice.';
|
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 = [];
|
$seen_quantities = [];
|
||||||
|
$old_unit = null;
|
||||||
foreach ($items as $delta => $item) {
|
foreach ($items as $delta => $item) {
|
||||||
$ingredient = \Drupal::entityTypeManager()->getStorage('asset')->load($item->target_id);
|
$ingredient = \Drupal::entityTypeManager()->getStorage('asset')->load($item->target_id);
|
||||||
$chemical_id = $ingredient->chemical_field->target_id;
|
$chemical_id = $ingredient->chemical_field->target_id;
|
||||||
|
$new_unit = $ingredient->unit_field->target_id;
|
||||||
if (isset($seen_quantities[$chemical_id])) {
|
if (isset($seen_quantities[$chemical_id])) {
|
||||||
$this->context->buildViolation($constraint->notUnique)
|
$this->context->buildViolation($constraint->notUnique)
|
||||||
->atPath($delta)
|
->atPath($delta)
|
||||||
->addViolation();
|
->addViolation();
|
||||||
}
|
}
|
||||||
|
if (isset($old_unit)) {
|
||||||
|
if ($old_unit != $new_unit) {
|
||||||
|
$this->context->buildViolation($constraint->notTheSameUnit)
|
||||||
|
->atPath($delta)
|
||||||
|
->addViolation();
|
||||||
|
}
|
||||||
|
}
|
||||||
$seen_quantities[$chemical_id] = true;
|
$seen_quantities[$chemical_id] = true;
|
||||||
|
$old_unit = $new_unit;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user