Drupal - How to display a node's last saved date?
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.
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.