0

I'm using the Drupal 8 Entity Validation API. I've implemented my Constraint and ConstraintValidator classes and added them as a constraint against the relevant entity field.

If I understand the validate method signature for ConstraintValidator correctly, I'm given a list of fields ($items) and the constraint ($constraint). However, I need to retrieve the parent entity in my logic.

How can I get the parent entity while with the validation API?

1

By using FieldItemList::getEntity like in this core validator:

Drupal\Core\Validation\Plugin\Validation\Constraint\UniqueFieldValueValidator:

class UniqueFieldValueValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    if (!$item = $items->first()) {
      return;
    }
    $field_name = $items->getFieldDefinition()->getName();
    /** @var \Drupal\Core\Entity\EntityInterface $entity */
    $entity = $items->getEntity();

The first argument of a validate method is of mixed type. For the Drupal Entity Validation API this can be a field value, a field item list or an entity, depending on where you add the constraint.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.