EntityHasFieldConstraintValidator.php

Same filename in other branches
  1. 9 core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/EntityHasFieldConstraintValidator.php
  2. 10 core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/EntityHasFieldConstraintValidator.php
  3. 11.x core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/EntityHasFieldConstraintValidator.php

Namespace

Drupal\Core\Entity\Plugin\Validation\Constraint

File

core/lib/Drupal/Core/Entity/Plugin/Validation/Constraint/EntityHasFieldConstraintValidator.php

View source
<?php

namespace Drupal\Core\Entity\Plugin\Validation\Constraint;

use Drupal\Core\Entity\FieldableEntityInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the EntityHasField constraint.
 */
class EntityHasFieldConstraintValidator extends ConstraintValidator {
    
    /**
     * {@inheritdoc}
     */
    public function validate($entity, Constraint $constraint) {
        if (!isset($entity)) {
            return;
        }
        
        /** @var \Drupal\Core\Entity\Plugin\Validation\Constraint\EntityHasFieldConstraint $constraint */
        if (!$entity instanceof FieldableEntityInterface) {
            $this->context
                ->addViolation($constraint->notFieldableMessage);
            return;
        }
        if (!$entity->hasField($constraint->field_name)) {
            $this->context
                ->addViolation($constraint->message, [
                '%field_name' => $constraint->field_name,
            ]);
        }
    }

}

Classes

Title Deprecated Summary
EntityHasFieldConstraintValidator Validates the EntityHasField constraint.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.