2

I know how get User entity changed time ($user->getChangedTime()).
Node has the same value ($node->changed), but I need to get this changed time from a Paragraph.

When I try this method $paragraph->getChangedTime() (the value changed do not exists) i got this:

Error: Call to undefined method Drupal\paragraphs\Entity\Paragraph::getChangedTime() ...

I have this field in my User entity, and I need to know when this field is changed. Is there any way to achieve that?

2
  • The Paragraph entity doesn't have a changed field. You need your own date field and fill it in a presave hook.
    – 4uk4
    Commented Apr 21, 2023 at 6:32
  • 1
    Paragraphs (and all entity reference revision fields) are directly tied to their parent entity, AFAIK their revisioning is completely tied to the host too. If you save the host, a new revision of all paragraphs is created, so a changed timestamp doesn't really make sense here by architecture of the module. If you need a separate changed timestamp, Paragraphs is the wrong tool.
    – Hudri
    Commented Apr 21, 2023 at 7:29

1 Answer 1

1

You can add a date/time field to the paragraph type and fill in the current time if the paragraph is changed:

mymodule.module

<?php

use Drupal\paragraphs\ParagraphInterface;
use Drupal\Core\Datetime\DrupalDateTime;
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

/**
 * Implements hook_ENTITY_TYPE_presave() for paragraph entities.
 */
function mymodule_paragraph_presave(ParagraphInterface $paragraph) {
  if ($paragraph->getType() == 'my_paragraph_type') {
    if ($paragraph->isChanged()) {
      $paragraph->field_date->value = (new DrupalDateTime('now', DateTimeItemInterface::STORAGE_TIMEZONE))
        ->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT);
    }
  }
}
2
  • I did not knew something like $paragraph->isChanged() existed. Is this paragraphs specific or can this be used with other entities too?
    – Hudri
    Commented Apr 21, 2023 at 10:48
  • This is specific to paragraphs but it's basically the same as if you would compare with $entity->original. So you could define a custom changed time for the content of a specific field or a set of fields in any entity.
    – 4uk4
    Commented Apr 21, 2023 at 11:23

Your Answer

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

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