5

Drupal 8 already displays the last saved date in page edit form. I want to add a field to a node that displays it again. I am using hook_form_alter() and doing this in my module, but it displays the current date.

  if ($form_id == 'node_page_edit_form') {
    $form['field_message2'] = array(
      '#type' => 'item',
      '#title' => t('Changed date'),
      '#weight' => -1,
      '#markup' => format_date(time(), $created),
    );
  }

How do I display the last saved date?

3

This is the code that you need:

    if ($form_id == 'node_page_edit_form') {
    $form['field_message2'] = array(
      '#type' => 'item',
      '#title' => t('Changed date'),
      '#weight' => -1,
      '#markup' => format_date($form_state->getFormObject()->getEntity()->changed->value),
    );
  }

Check the FormStateInterface interface to see in the methods the getFormObject() method.

3

The arguments you are passing a format_date() are wrong: The second argument is the format used for the date, not another timestamp.

You should code similar to the following one.

  if ($form_id == 'node_page_edit_form') {
    $node = $form_state->getFormObject()->getEntity();
    $form['field_message2'] = array(
      '#type' => 'item',
      '#title' => t('Changed date'),
      '#weight' => -1,
      '#markup' => format_date($node->getChangedTime(), 'medium'),
    );
  }

Even better, you should use the service Drupal provides for formatting dates.

  if ($form_id == 'node_page_edit_form') {
    $node = $form_state->getFormObject()->getEntity();
    $form['field_message2'] = array(
      '#type' => 'item',
      '#title' => new \Drupal\Core\StringTranslation\TranslatableMarkup('Changed date'),
      '#weight' => -1,
      '#markup' => \Drupal::service('date.formatter')->format($node->getChangedTime(), 'medium'),
    );
  }

Instead of 'medium', you can use the default value, or another one you prefer.

  • thanks for your answer Kiam, I will take note about this other way. – Adrian Cid Almaguer Jan 4 '17 at 16:20
  • Thank you, both of the above worked, but this caused a white screen =new TranslatableMarkup – paulcap1 Jan 4 '17 at 16:23
  • I have another question. I want to place another field below the changed date that will display 12 months added on to the changed date? (Add 1 year) This will be called a review date field. The content needs to be reviewed 12 months after the last changed date. – paulcap1 Jan 4 '17 at 16:27
  • @paulcap1 That is another question. – kiamlaluno Jan 4 '17 at 16:36
  • The WSOD is because you need to use the namespace of the class, not just the class name, or add a use statement at the beginning of the file. – kiamlaluno Jan 4 '17 at 16:42

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.