0

Address field is collection of other fields that one of them is postal_code. I wrote a custom validation constraint. It is applied and working. but the error message is showing for all fields of Address field, I just want it for Postal_code, how that is possible?

This is my ZipCodeValueValidator class

<?php

namespace Drupal\zip_code_lookup\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the Zip Code constraint.
 */
class ZipCodeValueValidator extends ConstraintValidator
{

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint)
  {
    foreach ($items as $item) {
      if ($this->validateZip($item)) {
        $errorMessage = "This is the new error message I wrote it.";
        $this->context->buildViolation($errorMessage)
        ->atPath('field_billing.postal_code')
        ->addViolation();
      }
    }
  }


  private function validateZip($value)
  {
    return TRUE;
  }
}

And here I set it to the field

<?php

use Drupal\Core\Entity\EntityTypeInterface;
/**
 * Implements hook_entity_bundle_field_info_alter().
 */
function zip_code_lookup_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle)
{
    if ($entity_type->id() === 'group') {
        if ($bundle == 'subscriber') {
            if (isset($fields['field_billing'])) {
                $fields['field_billing']->addConstraint('ZipCode', []);
            }
        }
    }
}

https://www.drupal.org/docs/drupal-apis/entity-api/entity-validation-api/providing-a-custom-validation-constraint

enter image description here

1
  • What i understand from your post is that you are specifying the field_billing field in which all the fields in address entity comes. Instead for you zip_code in Address enitity needs to be used for adding constraint Sep 28 at 8:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.