Score:0

How set violation to postal_code field on Address Fields

ye flag

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

Razeem Ahmad avatar
ru flag
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
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.