0

In my validator, I need to compare the new field value, that was submitted by the user, with the old value. How can I get the original value?

So far, I have this:

class CompareNewOldValuesValidator extends ConstraintValidator {

  public function validate($item, Constraint $constraint) {

    if (empty($item->getValue())) {
      return;
    }
    $value_new = $item->getValue()[0]['value'];

    /** @var ContentEntityInterface $entity */
    $entity = $item->getEntity();
    if (!$entity->isNew()) {
      $value_original = '???';
    }
  }
}    

I need to get the field value that was filled in the form before the user changed it, no matter if it is the active version or a draft or an old revision.

2 Answers 2

5

Normally the original entity is stored in the entity object before the user input is applied. If not, you can get it via the loaded revision id, which is preserved when an entity is loaded to keep it save from changes:

if (isset($entity->original)) {
  $original = $entity->original;
}
else {
  $original = \Drupal::entityTypeManager()
    ->getStorage($entity->getEntityTypeId())
    ->loadRevision($entity->getLoadedRevisionId());
}

$value_original = $original->{$item->getFieldDefinition()->getName()}->value;
1
  • In my case, $entity->original is not set. But then, the else part works as intended, so the overall solution works.
    – dxvargas
    Feb 15, 2021 at 14:51
2

I got the old value. I'll share my solution.

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;

class CompareNewOldValuesValidator extends ConstraintValidator {

  public function validate($item, Constraint $constraint) {

    if (empty($item->getValue())) {
      return;
    }
    $value_new = $item->getValue()[0]['value'];

    /** @var ContentEntityInterface $entity */
    $entity = $item->getEntity();
    if (!$entity->isNew()) {
      $entity_old = $this->entityRepository->loadEntityByConfigTarget($entity->getEntityTypeId(), $entity->getConfigTarget());
      $value_old = $entity_old->get($item->getName())->value;
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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