I have two fields, value
and copy
that I’m trying to do some custom validation on to make sure they roughly match each other.
So far in my module I have this:
function HOOK_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) { if(!empty($fields['field_value']) && !empty($fields['field_copy'])) { $fields['field_copy']->addConstraint('CopyMatchesValue'); $fields['field_value']->addConstraint('CopyMatchesValue'); } }
A constraint
<?php namespace DrupalMODULEPluginValidationConstraint; use SymfonyComponentValidatorConstraint; /** * Checks that value matches copy * * @Constraint( * id = "CopyMatchesValue", * label = @Translation("Copy Matches Value", context = "Validation"), * ) */ class CopyMatchesValue extends Constraint { // The message that will be shown if the format is incorrect. public $copyValueMismatch = 'The value does not look like it matches the copy.'; }
And a validator
<?php namespace DrupalMODULEPluginValidationConstraint; use SymfonyComponentValidatorConstraint; use SymfonyComponentValidatorConstraintValidator; /** * Validates the CopyMatchesValue constraint. */ class CopyMatchesValueValidator extends ConstraintValidator { /** * {@inheritdoc} */ public function validate($items, Constraint $constraint) { foreach ($items as $key => $item) { var_dump($item->value); } exit; // do some processing to make sure they match $this->context->addViolation(); } } }
I was expecting $items
to have both fields I added the constraint to, but that doesn’t seem to be the case.
How can I pass two fields to one validator so that I can validate them against each other?
Sponsored by SupremePR