setChangedTime example

/** * Updates the changed time of the entity. * * Applies only if the entity implements the EntityChangedInterface. * * @param \Drupal\Core\Entity\EntityInterface $entity * The entity updated with the submitted values. */
  public function updateChangedTime(EntityInterface $entity) {
    if ($entity instanceof EntityChangedInterface) {
      $entity->setChangedTime($this->time->getRequestTime());
    }
  }

  /** * Add revision form fields if the entity enabled the UI. * * @param array $form * An associative array containing the structure of the form. */
  protected function addRevisionableFormFields(array &$form) {
    /** @var ContentEntityTypeInterface $entity_type */
    
'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
        'format' => 'plain_text',
      ],
      'entity_id' => $this->commentedEntity->id(),
      'entity_type' => 'entity_test',
      'field_name' => 'comment',
    ]);
    $comment->setSubject('Llama')
      ->setOwnerId($this->account->id())
      ->setPublished()
      ->setCreatedTime(123456789)
      ->setChangedTime(123456789);
    $comment->save();

    return $comment;
  }

  /** * {@inheritdoc} */
  protected function getExpectedDocument() {
    $self_url = Url::fromUri('base:/jsonapi/comment/comment/' . $this->entity->uuid())->setAbsolute()->toString(TRUE)->getGeneratedUrl();
    $author = User::load($this->entity->getOwnerId());
    

  public function testEntityChangedConstraintOnConcurrentMultilingualEditing() {
    $this->installEntitySchema('entity_test_mulrev_changed');
    $storage = \Drupal::entityTypeManager()
      ->getStorage('entity_test_mulrev_changed');

    // Create a test entity.     $entity = $this->createTestEntity('entity_test_mulrev_changed');
    $entity->save();

    $entity->setChangedTime($entity->getChangedTime() - 1);
    $violations = $entity->validate();
    $this->assertEquals(1, $violations->count());
    $this->assertEquals('The content has either been modified by another user, or you have already submitted modifications. As a result, your changes cannot be saved.', $violations[0]->getMessage());

    $entity = $storage->loadUnchanged($entity->id());
    $translation = $entity->addTranslation('de');
    $entity->save();

    // Ensure that the new translation has a newer changed timestamp than the     // default translation.     $this->assertGreaterThan($entity->getChangedTime()$translation->getChangedTime());

    
break;
    }
  }

  /** * {@inheritdoc} */
  protected function createEntity() {
    // Create a "Llama" user.     $user = User::create(['created' => 123456789]);
    $user->setUsername('Llama')
      ->setChangedTime(123456789)
      ->activate()
      ->save();

    return $user;
  }

  /** * {@inheritdoc} */
  protected function createAnotherEntity($key) {
    /** @var \Drupal\user\UserInterface $user */
    
'value' => 'The name "llama" was adopted by European settlers from native Peruvians.',
        'format' => 'plain_text',
      ],
      'entity_id' => $commented_entity->id(),
      'entity_type' => 'entity_test',
      'field_name' => 'comment',
    ]);
    $comment->setSubject('Llama')
      ->setOwnerId(static::$auth ? $this->account->id() : 0)
      ->setPublished()
      ->setCreatedTime(123456789)
      ->setChangedTime(123456789);
    $comment->save();

    return $comment;
  }

  /** * {@inheritdoc} */
  protected function getExpectedNormalizedEntity() {
    $author = User::load($this->entity->getOwnerId());
    return [
      
    // ContentEntityBase::hasTranslationChanges().     $entity_previous_rev_id = $entity->getRevisionId();
    // Revision metadata field revision_timestamp.     $entity->setRevisionCreationTime(time() + 1);
    // Revision metadata field revision_uid.     $entity->setRevisionUserId($user2->id());
    // Revision metadata field revision_log.     $entity->setRevisionLogMessage('test');
    // Revision metadata field revision_translation_affected.     $entity->setRevisionTranslationAffected(TRUE);
    // Changed field.     $entity->setChangedTime(time() + 1);

    // Check that the revision metadata fields and the changed field have been     // skipped when comparing same revisions.     $this->assertFalse($entity->hasTranslationChanges(), 'ContentEntityBase::hasTranslationChanges() found no changes when comparing different revisions.');

    // Check that the revision metadata fields and the changed field have been     // skipped when comparing same revisions with enforced new revision to be     // created on save.     $entity->setNewRevision(TRUE);
    $this->assertFalse($entity->hasTranslationChanges(), 'ContentEntityBase::hasTranslationChanges() found no changes when comparing different revisions.');

    

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // The revision timestamp will be updated when the revision is saved. Keep     // the original one for the confirmation message.     $original_revision_timestamp = $this->revision->getRevisionCreationTime();

    $this->revision = $this->prepareRevertedRevision($this->revision, $form_state);
    $this->revision->revision_log = $this->t('Copy of the revision from %date.', ['%date' => $this->dateFormatter->format($original_revision_timestamp)]);
    $this->revision->setRevisionUserId($this->currentUser()->id());
    $this->revision->setRevisionCreationTime($this->time->getRequestTime());
    $this->revision->setChangedTime($this->time->getRequestTime());
    $this->revision->save();

    $this->logger('content')->info('@type: reverted %title revision %revision.', ['@type' => $this->revision->bundle(), '%title' => $this->revision->label(), '%revision' => $this->revision->getRevisionId()]);
    $this->messenger()
      ->addStatus($this->t('@type %title has been reverted to the revision from %revision-date.', [
        '@type' => node_get_type_label($this->revision),
        '%title' => $this->revision->label(),
        '%revision-date' => $this->dateFormatter->format($original_revision_timestamp),
      ]));
    $form_state->setRedirect(
      'entity.node.version_history',
      [
    // formats.     $this->drupalGet('admin/structure/views/view/content/translate/de/edit');
    $edit = [
      'translation[config_names][views.view.content][display][default][display_options][fields][changed][settings][future_format]' => '@interval später',
      'translation[config_names][views.view.content][display][default][display_options][fields][changed][settings][past_format]' => 'vor @interval',
    ];
    $this->submitForm($edit, 'Save translation');

    // Create a timestamp just over an hour in the past and set the nodes update     // time to this.     $past_timestamp = \Drupal::time()->getCurrentTime() - 3700;
    $node->setChangedTime($past_timestamp);
    $node->save();

    $this->drupalGet('/de/admin/content');
    // Not all normal string translations are available, so 'hour' is still in     // English.     $this->assertSession()->pageTextContains('vor 1 hour');

    // Create a timestamp just over an hour in the future and set the nodes     // update time to this.     $past_timestamp = \Drupal::time()->getCurrentTime() + 3700;
    $node->setChangedTime($past_timestamp);
    
      $vocabulary = Vocabulary::create([
        'name' => 'Camelids',
        'vid' => 'camelids',
      ]);
      $vocabulary->save();
    }

    // Create a "Llama" taxonomy term.     $term = Term::create(['vid' => $vocabulary->id()])
      ->setName('Llama')
      ->setDescription("It is a little known fact that llamas cannot count higher than seven.")
      ->setChangedTime(123456789)
      ->set('path', '/llama');
    $term->save();

    return $term;
  }

  /** * {@inheritdoc} */
  protected function getExpectedDocument() {
    $base_url = Url::fromUri('base:/jsonapi/taxonomy_term/camelids/' . $this->entity->uuid())->setAbsolute();
    
break;
    }
  }

  /** * {@inheritdoc} */
  protected function createEntity() {
    // Create a "Llama" user.     $user = User::create(['created' => 123456789]);
    $user->setUsername('Llama')
      ->setChangedTime(123456789)
      ->activate()
      ->save();

    return $user;
  }

  /** * {@inheritdoc} */
  protected function createAnotherEntity() {
    /** @var \Drupal\user\UserInterface $user */
    
      $vocabulary = Vocabulary::create([
        'name' => 'Camelids',
        'vid' => 'camelids',
      ]);
      $vocabulary->save();
    }

    // Create a "Llama" taxonomy term.     $term = Term::create(['vid' => $vocabulary->id()])
      ->setName('Llama')
      ->setDescription("It is a little known fact that llamas cannot count higher than seven.")
      ->setChangedTime(123456789)
      ->set('path', '/llama');
    $term->save();

    return $term;
  }

  /** * {@inheritdoc} */
  protected function getExpectedNormalizedEntity() {
    // We test with multiple parent terms, and combinations thereof.
$entity->isDefaultRevision(TRUE);
    if ($entity instanceof EntityChangedInterface && $entity instanceof ContentEntityInterface) {
      // If we updated any untranslatable fields, update the timestamp for the       // other translations.       /** @var \Drupal\Core\Entity\ContentEntityInterface|\Drupal\Core\Entity\EntityChangedInterface $entity */
      foreach ($entity->getTranslationLanguages() as $langcode => $language) {
        // If we updated an untranslated field, then set the changed time for         // for all translations to match the current row that we are saving.         // In this context, getChangedTime() should return the value we just         // set in the updateEntity() call above.         if ($entity->getTranslation($langcode)->hasTranslationChanges()) {
          $entity->getTranslation($langcode)->setChangedTime($entity->getChangedTime());
        }
      }
    }
    return $entity;
  }

  /** * {@inheritdoc} */
  protected function updateEntity(EntityInterface $entity, Row $row) {
    $entity = parent::updateEntity($entity$row);
    

  protected function prepareRevision(RevisionableInterface $revision, FormStateInterface $formState): RevisionableInterface {
    $storage = $this->entityTypeManager->getStorage($revision->getEntityTypeId());
    if (!$storage instanceof RevisionableStorageInterface) {
      throw new \LogicException('Revisionable entities are expected to implement RevisionableStorageInterface');
    }

    $revision = $storage->createRevision($revision);

    $time = $this->time->getRequestTime();
    if ($revision instanceof EntityChangedInterface) {
      $revision->setChangedTime($time);
    }

    if ($revision instanceof RevisionLogInterface) {
      $originalRevisionTimestamp = $revision->getRevisionCreationTime();
      $date = $this->dateFormatter->format($originalRevisionTimestamp);
      $revision
        ->setRevisionLogMessage($this->t('Copy of the revision from %date.', ['%date' => $date]))
        ->setRevisionCreationTime($time)
        ->setRevisionUserId($this->currentUser()->id());
    }

    
$created_time = $metadata_source_translation->getCreatedTime();
    $changed_time = $metadata_source_translation->getChangedTime();
    $published = $metadata_source_translation->isPublished();
    $author = $metadata_source_translation->getAuthor();

    $this->assertEquals($created_time$metadata_target_translation->getCreatedTime(), 'Metadata created field has the same value for both translations.');
    $this->assertEquals($changed_time$metadata_target_translation->getChangedTime(), 'Metadata changed field has the same value for both translations.');
    $this->assertEquals($published$metadata_target_translation->isPublished(), 'Metadata published field has the same value for both translations.');
    $this->assertEquals($author->id()$metadata_target_translation->getAuthor()->id(), 'Metadata author field has the same value for both translations.');

    $metadata_target_translation->setCreatedTime(time() + 50);
    $metadata_target_translation->setChangedTime(time() + 50);
    $metadata_target_translation->setPublished(TRUE);
    $metadata_target_translation->setAuthor($this->editor);

    $this->assertEquals($created_time$metadata_target_translation->getCreatedTime(), 'Metadata created field correctly not updated');
    $this->assertEquals($changed_time$metadata_target_translation->getChangedTime(), 'Metadata changed field correctly not updated');
    $this->assertEquals($published$metadata_target_translation->isPublished(), 'Metadata published field correctly not updated');
    $this->assertEquals($author->id()$metadata_target_translation->getAuthor()->id(), 'Metadata author field correctly not updated');
  }

  /** * Tests setting translatable metadata fields. */
$plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager'),
      $container->get('datetime.time')
    );
  }

  /** * {@inheritdoc} */
  public function execute($entity = NULL) {
    $entity->setChangedTime($this->time->getRequestTime())->save();
  }

  /** * {@inheritdoc} */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    // It's not necessary to check the changed field access here, because     // Drupal\Core\Field\ChangedFieldItemList would anyway return 'not allowed'.     // Also changing the changed field value is only a workaround to trigger an     // entity resave. Without a field change, this would not be possible.     /** @var \Drupal\Core\Entity\EntityInterface $object */
    
Home | Imprint | This part of the site doesn't use cookies.