added unit to ingredient with constraint
This commit is contained in:
@@ -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,
|
||||
],
|
||||
];
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user