I have a paragraph type with 2 fields: year and quarter
I have a content type with a paragraph field (field_year_and_quarter
) targeting ONLY this paragraph type
I am trying to create a constraint to disallow the encoding of a duplicate (same year/quarter)
I have tried:
1-A constraint at the node level which is looping into field_year_and_quarter
with $node->get('field_year_and_quarter')->referencedEntities()
to check if any duplicate
=>This is not working as it is not taking into account what is encoded in the widget, only the last saved version is checked
2-A constraint at the paragraph level which is getting its Parent to be able to loop into field_year_and_quarter
with $node_parent->get('field_year_and_quarter')->referencedEntities()
to check if any duplicate [I replace one item by the paragraph provided in the parameter ]
Here is the code:
public function validate($certificate_p, Constraint $constraint) {
/* @var \Drupal\paragraphs\Entity\Paragraph $certificate_p */
if ($certificate_p->bundle() == 'qoc') {
$prod_company = $certificate_p->getParentEntity();
$certificates = $prod_company->get('field_year_and_quarter')
->referencedEntities();
$all_certificates = [];
foreach ($certificates as $certificate) {
// use the paragraph provided in the function parameter
$certif_to_check = ($certificate_p->id() == $certificate->id()) ? $certificate_p : $certificate;
$year = $certif_to_check->get('field_qoc_year')->value;
$quarter = $certif_to_check->get('field_qoc_quarter')->value;
// Year/Quarter are already encoded
if (isset($all_certificates[$year][$quarter])) {
$this->context->addViolation($constraint->duplicate_certif, [
'%quarter' => surround_by_nbsp($quarter),
'%year' => surround_by_nbsp($year),
]);
break;
}
$all_certificates[$year][$quarter] = TRUE;
}
}
=>This is not working for the same reason
3- A constraint at the field level... here is the code:
public function validate($items, Constraint $constraint) {
$certificates = $items->referencedEntities();
$all_certificates = [];
foreach ($certificates as $certificate) {
$year = $certificate->get('field_qoc_year')->value;
$quarter = $certificate->get('field_qoc_quarter')->value;
// Year/Quarter are already encoded
if (isset($all_certificates[$year][$quarter])) {
$this->context->addViolation($constraint->duplicate_certif, [
'%quarter' => surround_by_nbsp($quarter),
'%year' => surround_by_nbsp($year),
]);
break;
}
$all_certificates[$year][$quarter] = TRUE;
}
}
=>Not working for the same reason
What should I do? (I have also tried to validate in the form without luck)